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;
    }
}

1 Answer

1

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
    }
  }
}