- Home /
How do I destroy an object when a certain number is reached? (Hit Points)
I'm trying to work on some basic AI and such. I just started learning it. Right now I'm trying to kill off an enemy (a box at this point) by reducing it's health to 0. When it reaches 0 or less, I want the object to be destroyed, but it's not working. Eventually I'll add things that modify the amount of dmg an enemy receives based off attack and such, but this little problem is holding up the whole operation.
Here's what I have JavaScript:
var Health = 100;
function update() { if (Health <=1) { Destroy (gameObject); }
}
function OnMouseUp() { Health -= 10; }
Unless I'm mistaken, the basic idea is there, but I'm missing something. The hit points drop correctly, but when it reaches 0 or less, the object still remains.
Answer by Eric5h5 · Apr 19, 2010 at 11:13 PM
The update function won't run automatically unless it's correctly named ("Update", not "update"). However, there's no need for that to be in Update in the first place, because Update runs every frame and you only need to check when the health actually changes. (Also, if you want it to be destroyed when the health is 0, it needs to be <= 0, not <= 1, which would destroy it if the health was 1.)
Thanks. Amazing what a typo can do with scripting...
@ Eric5h5, you said it doesn't have to be in Update? so is it better in Fixed Update? or where is the best to put that? :)
@Albert: FixedUpdate is only for physics. Just have a function that's called when the health is changed.