So I have two objects, i’ll call them b and c, and for some reason, even when c is closer to a than b, the Vector3.distance tells me b is closer to a.
foods = new GameObject[ ] { };
dino = GameObject.Find(“PH1”); //PH1 is a
private int FindClosest()
{
double min = 99999999999.00000000000000000;
int foodObject = -1;
for(int i = 0; i < foods.Length; i++)
{
double a = (dino.transform.position - foods*.transform.position).sqrMagnitude;*
Debug.Log(foods*.name + " " +a);*
if (a < min)
{
min = a;
foodObject = i;
Debug.Log(“changing min”);
}
Debug.Log(“end of loop”);
}
return foodObject;
}
The ideal scenario is returning c but it returns b. (c is green and b is red)
Your code even compile. (btw, please use the code tags Using code tags properly )
you can’t call “foods.transform.position”, foods is an array, you probably want “foods*.blah…” i being the loop iterator.*
why are you using doubles and not floats?
why are you comparing “a” against “99999999999.00000000000000000”, and why all the decimal places?
are you sure both objects are in the “foods” array?
As SparrowsNest commented your code doesn’t compile, because foods is an array and you first have to access a specific element inside the array to get to its properties. This is done via the [ ] operator, as in:
private int FindClosest()
{
double min = double.MaxValue;
int foodObject = -1;
for (int i = 0, l = foods.Length; i < l; i++)
{
GameObject food = foods[i];
double a = (dino.transform.position - food.transform.position).sqrMagnitude;
Debug.Log(food.name + " " + a);
if (a < min)
{
min = a;
foodObject = i;
Debug.Log("changing min");
}
Debug.Log("end of loop");
}
return foodObject;
}