x


GetComponent - Root Hierachy

Hello,

In my hierarchy I have a tank, within that tank (as a child) I have a health bar (plane).

Also in my hierarchy, I have a game empty with a script attached to it called 'Controller'.

Is there a way for my tank health bar script (which is attached to the health bar) to grab a variable from the Controller script?

Hierarchy:

  • GameEmpty / Controller

  • Tank / HealthBar / HealthBarScript

I don't want to use static variables. I was looking at the GetComponent, but that only seems to work when grabbing a variable on the object, or within (child).

Please help,

Thanks

more ▼

asked Jun 04 '11 at 07:29 PM

oliver-jones gravatar image

oliver-jones
2.5k 207 226 257

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

2 answers: sort voted first

You can either use GameObject.Find and GetComponent, or FindObjectOfType. If there's just one Controller script, then FindObjectOfType is more direct.

var controllerScript = FindObjectOfType(Controller);
controllerScript.someVariable = x;
more ▼

answered Jun 04 '11 at 08:22 PM

Eric5h5 gravatar image

Eric5h5
81.5k 42 133 529

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

It's somewhat tricky. In the HealthBarScript do the following:

  var ctrl:Controller = gameObject.GetComponent(Controller);
  // read or set any variable in Controller using ctrl:
  health = ctrl.Health;

I don't know if the var ctrl can be defined outside functions and initialised by Start(), but if it can be done it will optimize runtime performance.

more ▼

answered Jun 04 '11 at 08:02 PM

aldonaletto gravatar image

aldonaletto
42.5k 16 43 202

(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:

x422
x151
x27

asked: Jun 04 '11 at 07:29 PM

Seen: 982 times

Last Updated: Jun 04 '11 at 08:22 PM