- Home /
Why does this do nothing (Health Script)
var health : int = 10;
function OnCollisionEnter(collision : Collision)
{
if(collision.gameObject.tag == "Bullet")
{
health --;
Destroy(collision.gameObject);
}
}
function update(){
if (health < 0){
health = 0;
}
if (health > 10){
health = 10;
}
if (health == 0){
Destroy (gameObject);
}
}
Why is the GameObject not deleted and why does the health go below 0 ? :D
Answer by ExTheSea · May 02, 2013 at 07:18 PM
So if i were you i would change this script to something like this:
var health : int = 10;
function OnCollisionEnter(collision : Collision)
{
if(collision.gameObject.tag == "Bullet")
{
GetDamaged();
Destroy(collision.gameObject);
}
}
function GetDamaged(){
health --;
if(health<=0)
Destroy(gameobject);
}
Also i'm guessing that OnCollisionEnter won't get triggered if the player doesn't move while the bullet hits you as the player doesn't enter a collider.
That's why i would add this code to the bullet:
function OnCollisionEnter(collision : Collision){
if(collision.gameobject.tag == "Player")
collision.gameobject.SendMessage("GetDamage");
Destroy(gameobject);
}
Hope this helps.
Answer by HannesR · May 02, 2013 at 07:21 PM
It should be Update, not update, that's why it's not getting called ;-)
That's true but in his case i would still suggest him to remove the code in the update function because it the only time it really makes sense to execute is when the player actually gets hit. Otherwise it just unnecessarly affects your performance.