- Home /
Finding object with transform
I need to find a GameObject in the scene which has the same transform.postion.x
and transform.postion.z
as my other GameObject. Is there any better way to handle this than
foreach(GameObject go in GameObject.FindGameObjectsWithTag("myTag"))
{
if(go.transform.position.x == myObject.transform.position.x && go.transform.position.z == myObject.transform.position.z)
{
//Do something
break;
}
}
Answer by aldonaletto · Oct 07, 2011 at 09:22 PM
That's a really bad way to do this! Comparing float values rarely produces an equality due to limited internal precision: 2/10 is different from 0.2f, for instance.
You could use RaycastAll: cast a vertical ray at the xz position (but from a low y coordinate), then examine all objects returned - something like this:
Vector3 start = myObject.transform.position; start.y = -1000; // the ray must start at a very low y coordinate... RaycastHit[] hits = Physics.RaycastAll(start, Vector3.up); // and go up foreach (RaycastHit hit in hits){ // check the few objects returned if (hit.transform.gameObject != myObject){ // ignore myObject, of course // find the position difference in all 3 axes Vector3 diff = transform.position - hit.transform.position; diff.y = 0f; // ignore y difference if (diff.magnitude < 0.01f){ // accept a small error margin // do something } } }
Your answer
Follow this Question
Related Questions
transform.Find() returns a Transform? 1 Answer
GameObject.Find() Question 1 Answer
Finding Children question 3 Answers
gameobject.find custom class 0 Answers
C# How to move GameObject calling it by GameObject.Find(name) from another GameObject? 1 Answer