- Home /
Question by
fiercewaffle · May 27, 2011 at 06:20 AM ·
objectsfindseperate
Use of unassigned local variable `closest'
I am using this code in C# to determine the closest object to my pathfinding enemy with the tag "Player"
GameObject FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player");
GameObject closest;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
I am getting this error Assets/SimplePath/Examples/Code/Interaction_Chase.cs(62,16): error CS0165: Use of unassigned local variable `closest'
Comment
Answer by Ejlersen · May 27, 2011 at 06:38 AM
Set it to null, such that it has the possibility of returning null.
Thanks! Have been scratching my brain about this one! So simple...
Your answer
Follow this Question
Related Questions
Find objects by one tag or another. 3 Answers
I need to store the amount of objects in scene in a var. How? 1 Answer
GameObject.Find() work on inactive objects 16 Answers
FindObjectsOfType Problems 1 Answer
Finding objects on scene 1 Answer