- Home /
GetComponent in parent question
I know you can do GetComponent and it looks for other scripts in the same gameObject.
Then there's GetComponentInChildren which looks for scripts in the gameObject's children.
I was wondering if there was the same thing but for looking up in hierarchy like GetComponentInParent?
Or if GetComponent is already doing that.
Answer by JamesL98 · Nov 03, 2014 at 11:16 AM
GameObject.GetComponent("Name In hierarchy").GetComponent("Name Of Script/Controller");
This will find the object and then select the chosen script. The Name In Hierarchy can be a child of another game object and it will still select it without specifying that it is a child.
is it also possible to get the parent itself ? So that I can activate/deactivate it?
$$anonymous$$ind regards, Stefan
Why do you post a comment to this misleading and wrong answer? GetComponent can not find gameobjects, only components. He probably wanted to write GameObject.Find(). Even then this is a bad approach since you're bound to unique object names and it would be quite slow. Furthermore if you plan to deactivate the gameobject GameObject.Find won't find it again.
To access the parent of a gameobject, just use transform.parent.gameObject
. GameObjects do not have parents or child objects, only the Transform component builds up the hierarchy. When you look at Eric's answer at the top you'll see he suggested the same thing.
Next time when you have a question, please ask a seperate question. Though this is probably a too trivial question since just reading the documentation / manual should have answered your question. Also using google proberly should have given you this as the first result: How to disable parent through its own child object
Thanks for the answer! It´s not so easy for me to understand all the staff right and I am also new in Unity Program$$anonymous$$g. The documentation is often written for people who already have a lot of knowledge about program$$anonymous$$g in Unity. But thanks for the answer anyway :-)