You are comparing float
values directly ... never do that. It leads to a problem with the floating point precision. float
values are internally actually stored in increments of an Epsilon.
see e.g. from here
The nearest float
to 16.67
is 16.6700000762939453125
The nearest float
to 100.02
is 100.01999664306640625
or here for a broader explenation.
Use Vector3.Distance
!
Preferably with a certain threshold distance. There is an example that looks exactly like what you want to do in Coroutines (in JavaScript but the difference to c# in this case is minimal)
public float threshold = 0.1f;
//...
if(Vector3.Distance(gameObject.transform.position, array[i]) <= threshold)
{
....
}
Adjust threshold
so it has a value that is bigger than what the object can possibly move between two frames.
Or together with Mathf.Approximately
if(Math.Approximately(Vector3.Distance(object.transform.position, array[i]), 0.0f))
{
....
}
if your threshold is smaller than 0.00001
than you could also use
if(object.transform.position == array[i])
{
....
}
since ==
uses <= 0.00001
for equality.
But note: In the most cases the last two options will also fail because the opts for a moving GameObject to match an exact 3D position are almost 0 unless you set fixed values somewhere.
Vector3.Distance
also works with a Vector2
as parameter since an implicit typecast to Vector3
exists.