x


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?

more ▼

asked May 05 '12 at 12:23 PM

SGPascoe gravatar image

SGPascoe
20 5 6 9

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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);
}
more ▼

answered May 05 '12 at 12:59 PM

Piflik gravatar image

Piflik
5.4k 15 26 44

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!

May 06 '12 at 11:05 PM SGPascoe
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3682
x3328
x822
x405
x76

asked: May 05 '12 at 12:23 PM

Seen: 596 times

Last Updated: May 06 '12 at 11:05 PM