Run function once, is this method appropriate?

So, I am running an if statement through my Update function checking whether or not the player is dead, IF he is then run the PlayerDead function (show score, etc).

Obviously I only need to run it once and not every frame, so I wrote this piece of code – which works – though I am uncertain of whether or not this is appropriate / advisable.

I am quite new to programming and really have no clue about memory management, but I assume checking for an if statement every frame would be no different from Update checking if ANYTHING at all is happening every frame.

Thanks for any input you guys can afford. :slight_smile:

#pragma strict

private var runOnce : boolean = true;

function PlayerDead()
{
	player death stuff here
}

function Update()
{
	if(health == 0 && runOnce == true)
	{
		PlayerDead();
		runOnce = false;
	}
}

Hello bud, the above is absolutely fine.

If you really wanted you could change the “==” to “<=” just incase you ever have a situation where the health value may drop below 0, its a simple change, but can save you time if at any later stage you decide an enemy can give larger unequal damage to the player, say for example, each time your enemy hits the player, then 3 health points are knocked off, well if you player health was, for example, 10, then you would decrement beyond 0 after the player took 4 hits from that enemy then at the 4 hit, you would go below 0 … the above super minimal change to your conditional will still be valid.
Changed Version:

 if(health <= 0 && runOnce == true)
{
PlayerDead();
runOnce = false;
}

hope that helps some bud, but otherwise, you are doing great i`d say!
Cheers
Gruffy

i guess your player is restoring its health after death.

if you restore your player’s health in the PlayerDead() function you can do the check without the flag.

function PlayerDead()
{
    player death stuff here
    health = 999;
}
 
function Update()
{
    if(health <= 0)
    {
       PlayerDead();
       
    }
}