Find the closest gameobject ?

Ok, I have a Ai script that need to find the closest gameobject that is tagged by “Enemy”.

How should I do this ?

Raycast all around and find objects and store them in a array. How to find the closest object from the transfrom.position in the Array ?

OR another way to do this ?

Hi ,

why raycasting around if you already tagged your enemies ? You could just iterate through them with

// Quick Pseudocode

var allEnemies[] = GameObject.FindObjectsWithTag("Enemy");

For (var enemy in allEnemies)
{

  var pos = enemy.transform.position ;


    var dist = Vector3.Distance(pos, transform.position);
    
    print ("Distance to Enemy: " + dist);
}

There might be other ways, though.

–
oxl

OK, thanks

The raycast is to check if the player can see the enemies(If they are behind walls, not include them)

But could you explain the code you are using ?

what is the For(var enemy in allEnemies)

Thats looping through the array , you get returned by

FindObjectsWithTag(“Enemy”) ;

Maybe a “For (Next)” loop is more comfortable for you ?

Which language you are using ?

–
oxl

I’m using javascript.
Ok, is For(Next) the same as For(var enemy in allEnemies) ?

I didn’t understand the var enemy in allEnemies …

“var enemy” is one single enemy entry in the Array of Enemies per loop .

Something like :

For (var count ; count < Enemies.Length ; count++)
{

    var enemy = Enemies[count];

    // var pos = enemy.transform.position;

     //check distance etc
}

–
oxl

the “for enemy in allEnemies” simply means:
for each GameObject (lets call it enemy so that we can refrence it), in the list of GameObjects (which is called allEnemies) do the following code: …

it’s just a short way for looping through all items in a list, and it comes in handy when you don’t know how many elements you have in your list

ok, thanks for the explanation

but how do we know that enemy is one element in the enemies array ? Because of the tag ?

no… it’s not because of the tag… enemy here is just a variable
we could have just used something like:

	for (var x: GameObject in allEnemies) { 
		var pos = x.transform.position ; 
		var dist = Vector3.Distance(pos, transform.position);
                //extra code
	}

what happens here is that for every item in the allEnemies list:
in the first loop, x = allEnemies[0]
in the second loop, x = allEnemies[1]
… etc

as i said, x (or enemy) has nothing to do with the tag, it’s just a variable that holds a different item of the list each time

Ok, I get it now. Thanks

OK, then I have all the help I need to make a basic AI script. Finally understand a lot more about scripting :smile:

Thank you guys

I tried the script but get the error (UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.) :frowning:

ok… i don’t know what you did, but here is how i’d write it:

function Update() {
	var nearestEnemy : GameObject = Nearest("Enemy");
	var nearestCar : GameObject = Nearest("Car");
}



function Nearest(searchTag : String) : GameObject { 
   var allObjs : GameObject[] = GameObject.FindGameObjectsWithTag(searchTag); 
   var shortestDist : float = Vector3.Distance(allObjs[0].transform.position, transform.position);
   var nearestObj : GameObject = allObjs[0];
   
   for (var obj : GameObject in allObjs) { 
      var pos = obj.transform.position ; 
      var dist = Vector3.Distance(pos, transform.position); 
       
      if (dist <= shortestDist) 
         nearestObj = obj;
   } 
    
   return nearestObj;
}

hope this would help :smile:

yeah that helped, but the error was in

var allEnemies = GameObject.FindGameObjectsWithTag("enemy");

I couldn’t do FindGameObjectsWithTag when declaring the variable

yeah… if you want a variable to be fileld depending on what is available in the world, then you must do that inside a function (i don’t know why lol)
so… if you still want to use a public (or exposed variable), then use something like this:

var allEnemies : GameObject[]
function Update() {
       allEnemies = GameObject.FindGameObjectsWithTag("enemy");
       //rest of code
}

i think this would make it work… not sure lol

yeah I realized that after checking around

I ended up with this code today,but still going to add more

var enemies : GameObject[];
enemies = GameObject.FindGameObjectsWithTag("enemy"); 

var minDistance = 100; 
var closest : Transform; 

var smooth = 0.5;

for (var enemy in enemies) 
{ 
   var dist = Vector3.Distance(transform.position, enemy.transform.position); 
    
   if(dist < minDistance) 
   { 
      closest = enemy.transform; 
      minDistance = dist; 
   } 
} 



function Update () {
	transform.position = Vector3.Lerp(transform.position, closest.position, Time.deltaTime*smooth);
}