- Home /
Deduct health on collision
The last question went a bit off topic. This script I am writing is supposed to decrease the players health if anything with a tag of Enemy collides with it. It doesn't seem to do this and Im not sure what Im supposed to do, also if I could have some more help with having a timer so it only takes of damage every second or so, that would be great, thanks.
var fullHealth : int = 100;
var curHealth : int = 100;
function OnCollisionEnter(collision: Collision) {
if(collision.gameObject.tag == "Enemy");
curHealth -= 10;
print ("hit");
}
function Update () {
if(curHealth >= fullHealth){
curHealth = fullHealth;
}
if(curHealth <= 0){
curHealth = 0;
Debug.Log("You are Dead");
}
}
function OnGUI() {
GUI.Label (Rect (25, 40, 100, 20), "Health = "+curHealth);
}
originally from : http://answers.unity3d.com/questions/320641/taking-a-hit.html
Answer by GoCatGoGamesLLC · Sep 22, 2012 at 02:20 PM
It seems, at least from a logic perspective, that you are misusing "Full" and "Current" health levels. The "Full Health" represents the highest health level, a static number that should not be changed. "Current Health" is your bread and butter.
I'll make a leap and assume that your checking Current against Full in the Update to assure that Current never exceeds the maximum. I would change the second IF to reflect:
if ( curHealth <= 0 ) {
curHealth = 0;
Debug.Log ( "You are Dead" );
}
Similar issue in your OnCollisionEnter FUNCTION:
if ( collision.gameObject.tag == "Enemy" );
curHealth -= 10;
print ( "hit" );
}
Concentrate on using Current Health as your "working" health level and leave the Full Health variable to simply describe the maximum.
Hope that helps.
Edited to Add: You'll need to change your GUI as well (Full to Current).
Ive updated my code in the question but it doesn't change anything.
Answer by skalev · Sep 21, 2012 at 09:43 PM
This is bit confusing. First, is curHealth supposed to be the current health, then it is the one you should be editing, not the full health. also, I don't understand the purpose of checking if curHealth is => fullHealth. But that is aside the point. In any case, it should work fine with this code, what I would guess is the issue is that OnCollisionEnter is never called, so there is no hit. have you established that the function is called? (that is, do you see your hit debug message?)
The console never says that it gets hit which must mean its never called, how can I fix this?
Does any of your object has a rigidbody? I think you need at least one of them to have one.
Yeah, my enemy has a rigidbody, but adding one to my player changes nothing so it does not.
What kind of collider are you using? If mesh collider tick convex or better use a primitive collider like a box.
Your answer
Follow this Question
Related Questions
Taking a hit 3 Answers
Restart with GUIText 2 Answers
Adding a counter? 1 Answer
Setting Scroll View Width GUILayout 1 Answer
Need Help About Health,Damage 1 Answer