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;
}