getComponent() returns null if parent not active since instantiation

Hi all,

I’m trying to do a scripted menu, but have problems after instantiating a panel from a script.

Basically, I have a MyPanel, where buttons can be added. Within addButton() I am doing this:

    GameObject newButton = GameObject.Instantiate(templateButton) as GameObject;
    newButton.transform.SetParent(panel.transform, false);
    (newButton.GetComponent<Button>()).onClick.AddListener(() => { callback(param1); });
    RawImage ri = newButton.GetComponentInChildren<RawImage>();
    ri.texture = texture;  // Exception occurs here...

My panel is inactive in the beginning. When setting it active via setActive(true) before calling addButton() everything works fine. If not, ri is always null.

Do you have an idea why this is happening?
Is there some kind of validate() function I have to call before?

By the way: If not setting the panel as a parent, the NullReferenceException also doesn’t occur. Hope you can help me. Thanks in advance :slight_smile:

EDIT: So far I am calling setActive(true) before all addButton() calls and setActive(false) after them and it’s working, but is there another solution?

Unity has an overloaded version of GetComponentInChildren that takes a bool “includeInactive” you would call it like this:

GetComponentInChildren: “A component is returned only if it is found on an active GameObject.” Since it includes itself in search as well, it fails because it itself is disabled.

You would have to manually go through child transforms for inactive objects.

You can use GetComponentsInParent(true), it returns disabled game objects.