- Home /
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. :)
#pragma strict
private var runOnce : boolean = true;
function PlayerDead()
{
player death stuff here
}
function Update()
{
if(health == 0 && runOnce == true)
{
PlayerDead();
runOnce = false;
}
}
Thanks Gruffy! I am definitely going to make that change. Though I do have the health clamped between 0 and 999 I think you are right that I might as well check if for any reason at all the health goes lower than zero.
$$anonymous$$uch appreciated.
Not sure if I can change this question to answered, but, you answered, so cheers on you. ^_^ Thanks!!
Just changed it to answer for you bud, thanks much appreciated. Gruffy
Answer by onecolor · Mar 28, 2014 at 11:03 AM
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();
}
}
Interesting idea! Though, right now I have my health stored in a separate script with a set and get function. I am doing it this way simply because I needed to access the health from 3 different locations.
health display health decrement health increment
and set/get seemed like the best way to do it. (again I am new to program$$anonymous$$g, so there could very well be a better / easier way to do it -- though, to be truthful, I WAS using PlayerPrefs to store my health information >_> )
if you restore your health (in PlayerDead() or wherever) i think that the simplified if statement (without the flag) could works fine.
Thanks dude! Though, I guess I should have mentioned that I am not actually restoring health immediately after the player dies. The current game "session" ends, and the highscore and what have you is displayed.