- Home /
 
Can't use declared variable to find nearest Object
Hello everybody,
I want to "respawn" a player to the race track when he falls off the map and touches a trigger volume, this is my code :
 GameObject GetClosestObject(string tag) 
     {
         GameObject ClosestObject;
         GameObject[] gos = GameObject.FindGameObjectsWithTag(tag);
 
         float distance = Mathf.Infinity;
 
         foreach (GameObject go in gos) 
         {
             Vector3 diff = go.transform.position - transform.position;
             float curDistance = diff.sqrMagnitude;
 
             if (curDistance < distance) 
             {
                 ClosestObject = go;
                 distance = curDistance;
             }
         }
 
         return ClosestObject;
     }
 
               But I get this error in the last line :
error CS0165: Use of unassigned local variable `ClosestObject'
Anyone knows what I'm doing wrong?
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by robertbu · Dec 08, 2013 at 03:15 PM
On line 3, just do:
 GameObject ClosestObject = null;
 
               The compiler is complaining that if there is no objects in 'gos', then you will be returning an uninitialized 'ClosestObject'.
Your answer
 
             Follow this Question
Related Questions
C# Custom Class - Declare Variable's Value 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Variable References in C# from JS 1 Answer
Assigning current color to a variable for fade out (C#) 0 Answers