OnCollider script

I have this script on my car:

#pragma strict
publicvar hpPoints :float=3;
publicvarCurrentHP:float= hpPoints;
functionStart(){
}
functionUpdate(){
}
functionOnCollisionEnter(collision:Collision){
if(collision.gameObject.tag =="obstacle"){
CurrentHP-=1;
}
print("You have hit an object. "+"You have "+CurrentHP+"/"+ hpPoints +" HP points.");
if(CurrentHP==0){
print("You lost!");
}
}

The collider works, but everytime I hit an “obstacle”, it still says “You have 3/3 HP points”, instead of 2/3 or 1/3 or 0/3 (“You lost!”). I think it is a syntax problem. Does someone know ?

Try turning off your collider momentarily, then turning it back on.

Log the tag of your collider to ensure that it’s “obstacle”. Your log isn’t in the if but the deduction of HP is so the collision is working but the tag is most likely incorrect.

Hi. Thank’s for replying. Actually you are right, the tag was “Obstacle” instead of “obstacle” but now, I got another problem. When I start the game, without hiting anything, it gives me this:

The first one is 0/3 and the last 3/3 . Why ? Also, when I hit an obstacle, the first become -1/3 and the last 2/3, and so on.
I also modified my script a little bit:

#pragma strict
public var hpPoints : float = 3;
public var CurrentHP : float = 3;


function Start () {

}

function Update () {

}

function OnCollisionEnter(collision: Collision) {

if (collision.gameObject.tag == "obstacle"){
   CurrentHP -= 1;
}  
print("You have hit an object. " + "You have " + CurrentHP + "/" + hpPoints + " HP points.");

if (CurrentHP <= 0){
  print("You lost!");
 }

}

What can it be now ?

You must be hitting something to trigger it.

Negative numbers would be expected because you’re not doing anything to stop the subtraction of health when the health is already at 0. Also - if you’re adding/subtracting whole numbers just use integers instead of floats.

I know I have to hit something to trigger it, but as I said, it told me that I lost WITHOUT hiting anything, which is wrong.
I think the problem is my script, not how I use it.

That was my point. Unless you have code elsewhere that is causing a “loss” then you are hitting something :slight_smile: