- Home /
Health is set to zero at start of game.
I'm making a fighting game and, of course, it has health. I started the game with a static variable for the health.
static var Health1 = 1000;
But it didn't decrease when it collided with a projectile. So I decided to switch it to a regular variable and the health started out as 0! I figured that the problem didn't lie within the collision but within the health variable itself. Here's all of the references of "Health1" in my script.
var Health1 : int = 1000;
var Energy1 : int = 500;
function Update () {
//Limits your health.
if(Health1 > 1000){
Health1 = 1000;
}
if(Health1 < 0){
Health1 = 0;
}
}
function OnCollision(collision : Collision){
if (collision.gameObject.tag == "R_Projectile"){
//Receive variables from the attacker to properly calculate the outcome.
Damage = GetComponent(r_projectile2).Damage2;
Health1 = Health1 - Damage/DEF1;
Energy1 = ((Energy1 + Damage/DEF1)/2)*RATE1;
DMG1 = true;
}
}
I removed a good amount of script that doesn't affect the problem. Hope something can be found out here.
Answer by podmaster · Jul 04, 2014 at 04:02 PM
When you define your health variable do it like this
var Health1 : int ;
and set the value from the inspector, selecting the gameobject. and i recommend you to try also putting your if code this:
if(Health1 > 1000){
Health1 = 1000;
}
if(Health1 < 0){
Health1 = 0;
}
inside a function and call it after applying damage. and not from Update() maybe this is causing the problem too.
Answer by earrgames · Jul 04, 2014 at 04:03 PM
Ok, the problem is that that variable is set up from the inspector, it should be at "0", but you can better do this, Add this to your code:
function Awake(){ Health1 = 1000; }
Cheers!
Answer by Lazdude17 · Jul 04, 2014 at 04:01 PM
I don't think OnCollision is a method. You have to use OnCollisionEnter, OnCollisionStay or OnCollisionExit.
Also your projectile should be a trigger collider if it's not. If it is you need to change
OnCollisionEnter(collision : Collision)
to
OnTriggerEnter(collision : Collider)
and i recommend to create the collision function on the proyectile is easier to send the damage parameter then your player just have to run an "takeDamage" function.
Your answer
![](https://koobas.hobune.stream/wayback/20220613153253im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
guitexture a static var? 2 Answers
Increase Static Var gradually 1 Answer
How to use a static var 2 Answers
Static variables heavy for the iphone's CPU? 3 Answers
Static variables explanation. 2 Answers