Missing GameObject

Hi guys,

I made a turret gun that locks on to nearest target and shoots at it until its destroyed(dead) then searches for another target, it has a collider and a script which tells it to store every enemy gameobject that it collides with into a list of gameobjects and takes nearest as a target, and it works great, but for first 3-4 enemies, after that it just says Missing GameObject and it doesn’t want to switch to another target.

Here’s the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class shootbullets : MonoBehaviour
{
    public float cooldown = 0.2f;
    public float lastAttackedAt = 0.2f;
    public GameObject bullet;
     List<GameObject> NearGameobjects = new List<GameObject>();
     public GameObject closestObject;
    private float oldDistance = 9999;

    void Update()
    {
       FindNearest(); 
        
           if(Time.time>cooldown +lastAttackedAt)
        {
            Instantiate(bullet,transform.position,Quaternion.identity);
            lastAttackedAt = Time.time;
        }
    }

    void OnTriggerEnter2D (Collider2D col)
    {
        if(col.GetComponent<enemy_health>()!=null)
        {
            NearGameobjects.Add(col.gameObject);
        }
    }
   
    void OnTriggerExit2D (Collider2D col)
    {
        if(col.GetComponent<enemy_health>()!=null)
        {
            NearGameobjects.Remove(col.gameObject);
            
        }
    }

    public void FindNearest()
    {
        if(closestObject == null)
        {
            if(NearGameobjects.Count >0)
        {
             foreach (GameObject g in NearGameobjects)
        {
            if(g!=null)
            {
                float dist = Vector3.Distance(this.gameObject.transform.position, g.transform.position);
                if (dist < oldDistance)
            {
                closestObject = g;
                oldDistance = dist;
            }
            }
                       
        }
        }
        }
        
    }
    
}

The problem lies in the FindNearest() method. It’s not resetting closestObject and oldDistance when the current closest object is destroyed. Let’s modify the FindNearest() method to handle this properly.

public void FindNearest()
{
    closestObject = null;
    oldDistance = 9999;

    if (NearGameobjects.Count > 0)
    {
        foreach (GameObject g in NearGameobjects)
        {
            if (g != null)
            {
                float dist = Vector3.Distance(this.gameObject.transform.position, g.transform.position);
                if (dist < oldDistance)
                {
                    closestObject = g;
                    oldDistance = dist;
                }
            }
        }
    }
}

void Update()
{
    FindNearest();

    if (closestObject != null && Time.time > cooldown + lastAttackedAt)
    {
        Instantiate(bullet, transform.position, Quaternion.identity);
        lastAttackedAt = Time.time;
    }
}