Find Nearest Tag That's Using : Transform

I got the below example from the script reference, but it doesn’t seem to work with game objects that are using : Transform. How can I change it to allow me to do so?

I’m writing an AI system and all works fine, but there’s an Enemy and Ally system so they need to kill each other then move on to new targets without destroying it and getting a null reference.

Plus there can’t be more than one target or the AI won’t do anything. I was using this:

target = GameObject.FindWithTag ("Player").transform;

target = GameObject.FindWithTag ("Enemy").transform;

Here’s the script reference:

	// Print the name of the closest enemy

print(FindClosestEnemy().name); 

// Find the name of the closest enemy

  function FindClosestEnemy () : GameObject 

{

 // Find all game objects with tag Enemy

 var gos : GameObject[];

gos = GameObject.FindGameObjectsWithTag("Player"); 

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;    

  }

It isn’t as simple as the fact you are searching for “Player” in FindClosestEnemy?

I would have thought that this would also do it:

 import System.Collections.Generic;
 import System.Linq;

...
var target = GameObject.FindWithTag ("Player").transform;

 var closest = GameObject.FindGameObjectsWithTag("Enemy")
    .OrderBy(function(g) { return (g.transform.position - target.transform.position).sqrMagnitude;})
    .First();