- Home /
cannot convert `UnityEngine.GameObject' expression to type `System.Predicate< UnityEngine.GameObject >'
c# script
private GameObject[] GameObjSeen = new GameObject[50];
void Update()
{
foreach(GameObject Obj in GameObjSeen)
{
if(Vector3.Distance(Obj.transform.position,transform.position) > 60)
{
int i3;
i3 = System.Array.FindIndex(GameObjSeen,Obj);
GameObjSeen[i3] = null;
}
}
}
unity told me that:
Argument #2' cannot convert
UnityEngine.GameObject' expression to type System.Predicate< UnityEngine.GameObject >' and that: The best overloaded method match for
System.Array.FindIndex(UnityEngine.GameObject[], System.Predicate)' has some invalid arguments
what should i try?
replace
i3 = System.Array.FindIndex(GameObjSeen,Obj as GameObject);
with
i3 = GameObjSeen.indexOf(Obj);
You should be able to use IndexOf like so:
foreach(GameObject Obj in GameObjSeen)
{
if(Vector3.Distance(Obj.transform.position,transform.position) > 60)
{
int i3 = System.Array.IndexOf(GameObjSeen,Obj);
GameObjSeen[i3] = null;
}
}
But as @whydoidoit mentions, there is a much easier and faster way. You are already iterating over the array, it is much faster to just use a for loop:
for(int i=0; i<GameObjSeen.Length; i++)
{
GameObject Obj = GameObjSeen[i];
if(Vector3.Distance(Obj.transform.position,transform.position) > 60)
{
GameObjSeen[i] = null;
}
}
Answer by whydoidoit · Mar 28, 2013 at 08:52 PM
You need to specify a predicate function as either a method or a lamda.
I guess it would look something like:
i3 = GameObjSeen.FindIndex(o=>o == Obj);
But it would be easier and much faster to just do a for..next loop or keep an incrementing loop counter in your foreach loop.
i3 = System.Array.FindIndex(GameObjSeen,o => o== Obj); worked