When enemy dies the script loses object reference.

So I’m working on a little FPS and right now I have one enemy. When I kill that enemy it says "Object reference not set to an instance of the object. This is the area of code that the error is highlighting:

Vector3 firePointPos = new Vector3(firePoint.position.x, firePoint.position.y, firePoint.position.z);
        RaycastHit hit;
        Debug.DrawRay(firePointPos, transform.forward, Color.cyan);
        if (Physics.Raycast(firePointPos, transform.forward, out hit))
        {
            Debug.Log(hit.collider.tag);
        }
        Enemy enemy = hit.collider.GetComponent<Enemy>();

        if (enemy != null)
        {
            enemy.DamageEnemy(damage);
            Debug.Log("We hit " + hit.collider + " and did " + damage + " damage");
            
        }
    }`

More specifically it is highlighting this line:

Enemy enemy = hit.collider.GetComponent<Enemy>();

That line is outside of the if block, so it will run whether you hit a collider or not. So if the raycast fails, hit.collider = null, so it crashes.

You probably need to put everything in that first if statement:

     if (Physics.Raycast(firePointPos, transform.forward, out hit))
     {
         Debug.Log(hit.collider.tag);

         Enemy enemy = hit.collider.GetComponent<Enemy>();

         if (enemy != null)
         {
             enemy.DamageEnemy(damage);
             Debug.Log("We hit " + hit.collider + " and did " + damage + " damage");
         
         }
     }