Find nearest object (76351)

I need some help i am making a game in unity, i am trying to find the nearest object with the tag “Player” but the script is only finding the Player with the script attached to it anyone know how to fix this.

script:

// Print the name of the closest enemy
var Selfplayer : Transform;
print(FindClosestEnemy().name);

function Update() {
	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;    
}

Your question and your code comments are confusing. Are you trying to find the nearest GameObject tagged "Player" or "Enemy"; and are your players and enemies properly tagged? if you can find the closest (whatever) less frequently than every frame in Update(); do that. The more whatevers you have, the more this will slow your game down.

–

sorry if i confused you but what i am doing is putting this script on a Player (Who is a AI) so it can find the closest player but its only finding itself.

–

1 Answer

1

void Awake(){
InvokeRepeating(“FindClosestPlayer”, 0.5f,0.5f);
}

GameObject FindClosestPlayer() {
            gos = GameObject.FindGameObjectsWithTag("Player");
            distance = Mathf.Infinity;
            foreach (GameObject go in gos) {
                Vector3 diff = go.transform.position - transform.position;
                float curDistance = diff.sqrMagnitude;
                if (curDistance < distance) {
                    closest = go;
                    distance = curDistance;
                }
            }
            return closestPlayer;
        }

I used this in a script I have and works perfectly, since you are trying to find the enemy according to your question why is in the script FindGameObjectsWithTag(“Player”) is this supposed to be like this?

sorry but im still getting the same problem it thinks that the closest object is the object with the script on it.

–

maybe because the object with the script on it has the tag you are looking for, check that

–