Nulll Reference Problem with my missile script when all target is being Destroy

I have a missile script where i look for a target and then chase toward it but, after the target was remove the script giving me this error

NullReferenceException: Object reference not set to an instance of an object
Missile.FindClosestEnemy () (at Assets/Scripts/Player_Scripts/Missile.cs:63)
Missile.Start () (at Assets/Scripts/Player_Scripts/Missile.cs:19)

{



    public string searchTag;
    private GameObject closetMissile;
    public Transform target;
    public GameObject missileExpObject;
    public int _dmg;

    void Start ()
    {
        closetMissile = FindClosestEnemy ();
        if (closetMissile)
            target = closetMissile.transform;



        //if (target == null) {
        //    Destroy (this.gameObject);
            //transform.position = Vector3.up * 10f * Time.deltaTime;

    //    } else {
       
       
        //}
    }

    void Update ()
    {


        if (target != null) {
            Vector3 dir = target.transform.position - transform.position;
            float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg - 90;
            transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
            //transform.Translate (Vector3.forward * 5.0f * Time.deltaTime);
            Rigidbody rig = GetComponent<Rigidbody> ();
            rig.velocity = transform.position = Vector3.MoveTowards (transform.position, target.transform.position, 10f * Time.deltaTime);
   
        } else {
           
           
        }

    }

    GameObject FindClosestEnemy ()
    {
        GameObject gos;
        gos = GameObject.FindGameObjectWithTag (searchTag);

        GameObject closest = null;
        float distance = Mathf.Infinity;

        Vector3 position = transform.position;
            Vector3 diff = gos.transform.position - position;
            float curDistance = diff.sqrMagnitude;

            if (curDistance < distance) {
                closest = gos;
                distance = curDistance;
            }

        return closest;
    }

My guess would be that you’re only setting the target on Start() which runs once, so it will find closest target and then when that target it destroyed it gives a null reference. You are also returning a null object in your “FindClosestEnemy()” method, you are returning a gameobject called “closest” but the value is always null. You may want to try something like this to make things a little simpler:

private bool IsInRange()
{
    return Vector3.Distance(target.position, missile.position) < distance;
}

Hope this helps

-Joshmond

If gos doesn’t find anything with that tag, it will be null. Thus, most likely your error as you try to access it’s transform even if it doesn’t exist.

when i add return null or if(object != null) FindClosestEnemy();