V
V
Vqrlamov2022-01-04 17:39:49
Unity
Vqrlamov, 2022-01-04 17:39:49

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


And one more question, if it doesn't make it difficult, how can you add a zone, when entering which the player will look at the nearest enemy?
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2022-01-04
@Vqrlamov

But if Destroy of any enemy occurs, unity will throw a MissingReferenceException

Because it is necessary to remove it from the array too. By any means.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question