I am trying to return a Vector3, But I don’t know why its not working.
I remember when doing something like this with GameObjects I needed to set the GameObject to null, I tried this with the Vector3 but it didn’t work, Any ideas?
public Vector3 FindClosestTileVector3() {
Vector3[] vectors;
vectors = tiless.ToArray();
Vector3 closestVector;
float distance = Mathf.Infinity;
Vector3 position = cursor.transform.position;
foreach (Vector3 v in vectors) {
Vector3 diff = v - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closestVector = v;
distance = curDistance;
}
}
return closestVector;
}
The way the script/code is currently, you will only return the last(if at all) that the variable closestVector was set, you have no loop control going on there. Unless you want the last time it was set…
Also by not working, what do you mean, error? null? weird value?
Error: Assets/Scripts/ILYTM_Logic.cs(252,16): error CS0165: Use of unassigned local variable `closestVector’
What I wanted to do is Find the closest Vector3 to the mouse in my tiles array… On the Docs there was an example of Finding the closest GameObject, So I thought just changing it to Vector3’s would do the same…
there’s no guarantee closestVector will be set in that loop. So you need to set the vector to something before that for loop. So if no vector is found some default value is used.
So as CrazySi says, in the vector’s declaration. Set it to Vector3.zero. Guaranteeing SOMETHING will be returned even on failure.