- Home /
health bar referencing another scripts variable
This is the health script that Im using.
var health : playerhealth = gameObject.GetComponent(playerhealth);
var initialGreenLength: float;
var greenBar: GameObject;
var helth: int = health.HP;
var maxHealth: float=100;
function Awake(){
helth=maxHealth;
initialGreenLength=greenBar.transform.localScale.x;
}
function Update(){
greenBar.transform.localScale.x=initialGreenLength*(helth/maxHealth);
}
The
var health : playerhealth = gameObject.GetComponent(playerhealth);
section of the script references another scripts variable of player HP, but it doesn't seem to be working. This is the other script
var HP : int = 5;
var body = gameObject;
function Update () {
if(HP < 1) {
var instance : GameObject = Instantiate(body, transform.position, transform.rotation);
DestroyObject (gameObject);
}
}
How do I fix it so it works?
Whats currently going wrong? Do you have an error message or what is not happening that you think should be.
It was spelled helth because health was already a variable
Answer by eeveelution8 · Apr 03, 2014 at 07:42 PM
I figured out how to fix it, I deleted the HP bar script, made a GUIText, and changed the player health script to look like this,
var gui : GUIText = gameObject.GetComponent(GUIText);
var HP : int = 5;
var body = gameObject;
function Update () {
gui.text = "Health: "+HP;
if(HP < 1) {
var instance : GameObject = Instantiate(body, transform.position, transform.rotation);
DestroyObject (gameObject);
}
}
thanks everyone for the help though.
Answer by FirePlantGames · Apr 03, 2014 at 03:25 AM
var health : playerhealth = gameObject.GetComponent(playerhealth);
should be: var health : int = gameObject.GetComponent(playerhealth).HP;
If I understand you correctly, also "playerhealth" needs to be the 'destroy' scripts name
I tried what you suggested, but it comes up with the error,
transform.localScale assign attempt for 'healthbar' is not valid. Input localScale is { NaN, 1.000000, 0.005000 }. UnityEngine.Transform:set_localScale(Vector3) hp counter:Update() (at Assets/scripts/hp counter.js:17)
Answer by alti · Jun 25, 2014 at 06:30 AM
This probably happened because Helth or MaxHealth was == 0. One rule in math: You cannot divide by 0. If you do something like:
(Helth + 0.0001)/(MaxHealth + 0.0001); You would be good (add the 0.001 to whatever could potentially be 0).
Your answer
Follow this Question
Related Questions
Can someone write me a health script? 2 1 Answer
How to Make Health Decrease Over Time 2 Answers
Enemy Health Help 1 Answer
Why don't my send messages work? 2 Answers
Enemy Health Problems 1 Answer