- Home /
Get children of another object in hierarchy.
Hello, I want to get children objects of another object in hierarchy which does not contain script in which I'm coding, and then disable the children objects through code:
SetActive(false);
Let's say my script is attached to an object called "GameManager" and I want to get children objects of an object called "MenuPanel" and disable them.
How do I do it? I don't see any function which allows me to do it. I can only see GetComponentsInChildren etc. but I want don't want to get components, I want to get CHILDREN OBJECTS. I tried getting component GameObject but it seems it is not a component.
Try get the Transform then access to the game object trough this.
Answer by mujpir · Mar 16, 2019 at 10:36 PM
As @Masterio said , You should first find the gameObject you want to set its children to be disabled . So use GameObject.Find("MenuPanel") to find the MenuPanel object , Then use its transform to access its childs and then disable theme like this :
var menuPanelTransform = gameObject.Find("MenuPanel").transform;
menuPanelTransform.FindChild("child_0").gameObject.SetActive(false);
If you can , reference "MenuPanel" gameobject in your script , So you don't have to find it every time.
The best solution for this as @mujpir said is using the references:
$$anonymous$$ake an handle variables for all important objects like : $$anonymous$$enuPanel 0, $$anonymous$$enuPanel 1, ... Pause$$anonymous$$enu, etc.
Example:
public GameObject menu_0;
public GameObject menu_1;
public GameObject menu_2;
Then when you want to activate one of it just execute the code:
public void Show$$anonymous$$enu(int menu_id)
{
switch(menu_id)
{
case 0 :
{
menu_0.SetActive(true);
menu_1.SetActive(false);
menu_2.SetActive(false);
break;
}
case 1 :
{
menu_0.SetActive(false);
menu_1.SetActive(true);
menu_2.SetActive(false);
break;
}
case 2 :
{
menu_0.SetActive(false);
menu_1.SetActive(false);
menu_2.SetActive(true);
break;
}
}
}
You can use an array for game objects if you are using a lot o menus and activate wanted menu by the array index.
@mujpir, @$$anonymous$$asterio I have to do it for every single child? I thought of making an array and then do foreach loop and disable them but I guess It's not possible. Is there a way to get every single child of an object? If not, will it work with RectTransform component?