- Home /
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
Answer by Eric5h5 · Jun 04, 2011 at 08:22 PM
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;
Answer by aldonaletto · Jun 04, 2011 at 08:02 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612095345im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
OnBecameVisible() .. GetComponent(ScriptName) 0 Answers
PowerUp mechanics doesn't works 0 Answers
Access component of parent with multiple children 2 Answers
Is it possible to get all root transforms of the scene hierarchy? 2 Answers
transform.root and empty root game objects don't play nice 1 Answer