Answer the question
In order to leave comments, you need to log in
How to solve the problem with finding nearby enemies?
Hello, there is a script and there is a problem. Found a script on the Internet. The script determines which enemy is closest to the player. But if Destroy of any enemy occurs, unity will throw a MissingReferenceException
using UnityEngine;
public class FindClosestEnemy : MonoBehaviour
{
GameObject[] enemy;
GameObject closest;
public string nearest;
void Start()
{
enemy = GameObject.FindGameObjectsWithTag("Enemy");
}
GameObject FindClosestEnemies()
{
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in enemy)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
void Update()
{
nearest = FindClosestEnemies().name;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question