- Home /
Health won't update in GUI
Basically, I'm trying to make it so that this code updates my GUI to keep track of how much health the player and enemy has. Only problem is that it won't update the GUI, it just stays at 2. The print quotes output the correct health in the console, but not in the GUI. I've only attached this script to my CannonBall and my GUI Text file. Any help would be much appreciated.
var hpPlayer : int = 2; var hpEnemy : int = 2; var playerDead : boolean = false; var enemyDead : boolean = false; var x = 1;
function OnTriggerEnter(hit : Collider) { if (collider.gameObject.tag == "CannonBall") { Destroy(collider.gameObject); } }
function OnCollisionEnter(collision : Collision){ if(collision.gameObject.tag == "Player"){ hpPlayer--; print("hit player " + hpPlayer); if (hpPlayer<=0) playerDead = true; }
if(collision.gameObject.tag == "Enemy"){
hpEnemy--;
print("hit enemy " + hpEnemy);
if (hpEnemy<=0) enemyDead = true;
} }
function OnGUI () { hpP = hpEnemy + ""; GUI.Label (Rect (10, 10, 100, 20), "HP Player: " + (hpPlayer).ToString()); GUI.Label (Rect (10, 30, 100, 20), "HP Enemy: "(hpEnemy).ToString()); }
Add a print statement in an Update Function and see if 'hp' is actually moving.
I can already tell that hp isn't moving by looking at the inspector. I just have no idea because my other print function is showing that it went down by one, when the inspector isn't.
Answer by coastwise · Dec 14, 2010 at 03:53 PM
Your trouble lies in the fact that this script is instantiated once for every GameObject it is attached to. The instance that is attached to your GUI has its own copy of the hpPlayer
and hpEnemy
variables, and since the GUI is never colliding with the player, these copies that are being displayed are never being modified.
Additionally, I'm assuming your using Instantiate
on each of your cannon balls. Each of these will also have their own copy and you have the same problem.
The quick fix here is to declare those shared variables as static
, that way there is only one copy that is shared between every instance of the script. Check out this explanation from the Script Reference.
Your answer
![](https://koobas.hobune.stream/wayback/20220613090424im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Input versus Event 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Setting Scroll View Width GUILayout 1 Answer
Is it possible to link character skill lists to a GUI, and if so, how? 3 Answers
Windows Application 2 Answers