Making the enemy shoot only when player is alive

I’m making a pretty simple bullethell game, and I would like the enemy to stop shooting when my player dies(it is active when alive, and not active when dead). I don’t know where I fail in the code. It gives me a NullReferenceException when my player dies (gets deactivated).


    var enemyLaser : GameObject;
    var fireFreq : float;
    var projectileSpeed:float = 0.0;
    private var lastShot : float;
    
    function Update () {
    	if (Time.time > lastShot + fireFreq){
    		Fire();
    		}
    }
    
    function Fire() {
    	lastShot = Time.time;
    	var player = GameObject.Find("player");
    		if (player.active){
                        var shoot = Instantiate(enemyLaser,transform.position,transform.rotation);
    			shoot.rigidbody.velocity = (player.transform.position - transform.position).normalized * projectileSpeed;
    			}
    }

when deactivated it cant acces it. you could solve it by having an boolean in the player’s script. and checking that value (if its alive or not)

If you’re destroying or disabling the player when they die, then GameObject.Find wil no longer find that object. So after this line…

var player = GameObject.Find("player");

The player variable will be null, then when you reference the player.active property…

		if (player.active)

you’ll get a null reference exception. You can fix it by changing your if statement…

if (player != null && player.active)
{
   ... your stuff here ...
}

So it will only execute the code inside if when the player object is found.