Sunday, June 26, 2011

destroy an object when a certain number is reached? (Hit Points)


This is captured from Unity Answers
====================================================================================================================================================================
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;
}
========================================================================================
Algorithms is wrong and needs to be corrected
=========================================================================================
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.)


==================================================================================
Correct Algorithm
================================================================================

var Health = 100;
function Update() {
CheckHealth(); }
function CheckHealth() {
if (Health <=0) { Destroy (gameObject); } }
function OnMouseUp() { Health -= 10; }

No comments:

Post a Comment