- Home /
How would I be able to subtract from a variable when it hits something? (OnCollisionEnter)
I have been learning Javascript and I was wondering if I could subtract a variable if the game object came in contact with a certain object. For example, if an enemy touched the character, it would say GAME OVER. Something along those lines.
Answer by Sajidfarooq · Aug 15, 2013 at 06:08 AM
Yes, its quite simple.
a) Make sure the the character, and the collided object both have colliders attached.
b) Make sure that at-least one of them is a (non-kinematic) rigid-body, generally the character.
Remember that "OnCollisionEnter" will not work with the built-in "CharacterController" that comes with Unity. For that you will need to use "OnControllerColliderHit" instead.
#pragma strict
var Health:int =10;
function OnCollisionEnter(collision : Collision)
{
if(collision.gameObject.tag == "Monster")
{
Health = Health-1;
Debug.Log("Health reduced to " + Health);
}
if(Health <= 0)
{
Debug.Log("Character died");
}
}
This is great! Thank you so much! I see now what I was doing wrong. Thanks again!
Please remember to mark this question as "answered" if you are satisfied with the answer.