Cannot convert UnityEngine.GameObject to UnityEngine.GameObject
I'm using Linq.Where to filter objects in a list to find a object with a specific location like so:
Vector3 targetPosition = new Vector3(1,2,3) ;
GameObject go = TerrainObjs.Where ( obj => obj.transform.position == targetPosition ) ;
results in the error: "error CS0029: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable[UnityEngine.GameObject]' to 'UnityEngine.GameObject' "
I'm not sure if/what i did wrong, or a way around this. Built-in conversions don't work and that's pretty much the limit of my knowledge. I'm a bit of a noob with Linq.Where and I'm trying to clean up my code with more compact techniques.
Answer by mikelortega · Nov 30, 2015 at 11:11 AM
Where returns a list of elements, not a single GameObject as you expect.
IEnumerable<GameObject> gos = TerrainObjs.Where(obj => obj.transform.position == targetPosition);
foreach (GameObject go in gos)
; // do what you need with go
On the other hand, you should not compare positions with "==". Doing it that way you will have problems with float precision (two elements in the same place can have slightly different numeric representations). You should subtract vectors and check magnitude (distance).
Thanks for the info. I wasn't aware that it returned a list. I'm actually comparing positions cast as ints in an int[2], so the floating point wouldn't be an issue. I was just being lazy in the example by putting a Vector3 there, so i didn't have to explain the conversion.