- Home /
health and damage system help
Hi im trying to make a simple health system that will cause the player to lose 10 hp if he walks into a ball. But i cant get it to work, here is my code so far
var curHealth : int = 50; //set current health
var maxHealth : int = 100; //set max health
var healthPerSec : int = 1; // health regen per second
var alive : boolean = true; // set the player to alive
//not working
function OnCollisionHit(hit : Collider) {
if (hit.gameObject.CompareTag == "ball"){
curHealth -= 10;
}
}
function Update () {
//tets if player should be alive
if(curHealth <= 0){
alive = false;
}
}
function Start () {
autoHealthRegen();
}
// regen health
function autoHealthRegen () {
for(var e=1;e>0;e++) {
yield WaitForSeconds(1);
if(curHealth < maxHealth) {
curHealth= curHealth + healthPerSec;
}
}
}
Format your code a bit better please. Did you mean to use OnTriggerEnter(hit : Collider)
or OnCollisionEnter(hit : Collision)
?
Answer by EvilWarren · Oct 24, 2013 at 10:44 AM
This line is wrong
if (hit.gameObject.CompareTag == "ball"){
You are comparing a function with a string, allowed because of UnityScript loose typing.
You want to use either
if (hit.gameObject.CompareTag("ball")){
or
if (hit.gameObject.tag == "ball"){
Also, did you check out @vexe's comment above?
That's cause you're using OnCollisionHit, there's no such thing. See my comment above.
collision only works if at least one of your two colliders have a rigidbody. what do the two colliding objects you have attached to them?
If this script is attached to a character controller, then you must use OnControllerColliderHit.
i have been given this error
OnControllerColliderHit couldn't be called because the expected parameter Collision doesn't match ControllerColliderHit.
UnityEngine.CharacterController:$$anonymous$$ove(Vector3)
Character$$anonymous$$otor:UpdateFunction() (at Assets/Standard Assets/Character Controllers/Sources/Scripts/Character$$anonymous$$otor.js:229)
Character$$anonymous$$otor:FixedUpdate() (at Assets/Standard Assets/Character Controllers/Sources/Scripts/Character$$anonymous$$otor.js:331)
code:
function OnControllerColliderHit(hit : ControllerColliderHit){
if (hit.gameObject.CompareTag("Ball")){
curHealth = curHealth - 5;
}
}
Great, accept the answer above, and upvote any comments that you found useful, since I spent more than 2 hours giving you support. Thanks.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Enemy deals damage to player on contact 2 Answers
Damage on collision problems... 0 Answers
How Can One Collider Recognize Contact With Another? 0 Answers
Don't restart music on death 2 Answers