I have a script (from the Unity docs) that checks the nearest enemy. The script works fine but it only checks every object (enemy) ones. When the player moves close to a previous object the script does not detect (update) it.
Script:
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("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;
}
I think it has to do with the for loop that is not being reset. Can someone please help me with this?
Hi I having a same issue Frido. but I tried the way that is being mentioned. like putting inside a fixedupdate but still nothing happened it still detect my first object only. Even i move near to the other object it still does not update to the other object that i am near it.
So frido can i ask how you solve the issue. Thanks.
I used this code, and it works perfectly. Of course, you have to actually do something with the GameObject that gets returned from calling this function, but here it is:
// Find the closest enemy
function FindClosestEnemy () : GameObject {
// Find all game objects with tag Enemy
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Enemies");
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;
}
So for example, you could have something similar to this in Update:
function Update() {
if (Input.GetMouseButton(1))
{
isEnemyTargeted = true;
targetedEnemy = FindClosestEnemy();
DeselectOtherEnemies();
var script : MouseInteractionObject = targetedEnemy.GetComponent(MouseInteractionObject);
script.isSelected = true;
}
}
This makes it so if you click the Right Mouse button it targets the closest enemy. It then sets isSelected to true on a script called MouseInteractionObject that is attached to all Enemies. You can then do something to the enemy if isSelected = true. I also have a function here called DeselectOtherEnemies() that goes through and deselects all of them before selecting the single correct one.