- Home /
Get variable from another object
I've been looking around for information on this, but the reference keep confusing me.
All I want to do is set my GUI to display the health of my player.
So I have an object named PlayerModel,with a script named Health, with a variable named health.
I then have an empty gameobject I named GUI, and it needs to set var health to.. the player's health!
I tried:
private var health = Health.health;
function OnGUI ()
{
GUILayout.Label("HP:" + health);
}
but that reports 100 constant. I'm guessing the key is to refer to the PlayerModel with GetComponent somehow?
Answer by Piflik · May 05, 2012 at 12:59 PM
The problem is, that the health variable is set to the player's health at the start and never modified. You have to either update the health variable periodically, or simply display the Health.health variable directly:
function onGUI() {
GUILayout.Label("HP: " + Health.health);
}
I see! Awesome! So it just needed updating! I take it my script called the health at the start and wasn't ever prompted to update.
I have it fixed now, but one more question.
What if I have the Health script on two separate objects? (one for player, and one for enemy) how would I update or track a variable on each one separately?
Thanks so much for your help! I think I'm learning quickly!
Your answer
Follow this Question
Related Questions
GetComponent Help 2 Answers
How can i make GetComponent(SCRIPT) apply to ONLY ONE object that has the script? 1 Answer
Can't understand generic getComponent for Js 1 Answer
How could you access a script of varying name? 5 Answers
How to set a variable equal to another variable in another gameobject? 2 Answers