- Home /
 
Finding Closest Enemy...
I am trying to make a script that finds enemies closest to my player.
Here is what I have ;-
 function FixedUpdate(){
 Debug.Log(FindClosestEnemy().name);
 }
 
 // Find the closest enemy 
 function FindClosestEnemy() : GameObject { 
     // Find all game objects with tag Enemy 
     var gos : GameObject[]; 
     gos = GameObject.FindGameObjectsWithTag("Enemy"); 
     var closest : GameObject; 
     var distance = Mathf.Infinity; 
     var position = transform.position; 
     // Iterate through them and find the closest one 
     for (var go : GameObject in gos) { 
         var diff = (go.transform.position - position); 
         var curDistance = diff.sqrMagnitude; 
         if (curDistance < distance) { 
             closest = go; 
             distance = curDistance; 
         } 
     } 
     return closest; 
 }
 
               My problem is that the player detects the first enemy and then the second (it gets printed) but when i move back to the first one.. the print doesn't update.. Please help..
I don't see anything wrong there... $$anonymous$$aybe I'm missing it, too.
that's the exact script from the unity website http://unity3d.com/support/documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html
Answer by Waz · Jul 13, 2011 at 09:25 PM
Do you have "Collapse" turned on in your Console window? The code is right, so it's something like that.
Answer by jainischalverma · Jul 13, 2011 at 10:08 PM
Warwick... you were right! Its printing now. After I turned off collapse... lol...what a small thing...
In the future, please don't post comments as answers; ins$$anonymous$$d, use your original question or its comment area.
Your answer