Delaying the Start function of an entire GameObject's hierarchy

Hello,

I am creating a GameObject hierarchy over many frames, with many Components on various children GameObjects.
I want to delay initialization until the whole hierarchy is created, however simply disabling the root GameObject isn’t preventing newly created Components on its children from calling Start. Is the only way to postpone Start by disabling every GameObject with a script?

Cheers

I realize disabling the root object does indeed halt Start for its entire hierarchy; my scripts had errors. Yay

Hello,
Here is my code it is working correctly.

    bool initialized = false;

    // Update is called once per frame
    void Update()
    {
        if (this.transform.parent.gameObject.activeSelf)
        {
            FunctionCalledByButton();
        }
                if (this.transform.parent.gameObject.activeSelf && !initialized)
        {
            InitializeFunction();
            initialized = true;
        }
    }

    void FunctionCalledByButton()
    {
        Debug.Log("Function being called while the parent is active.");
    }

    void InitializeFunction()
    {
        Debug.Log("Function called only one time.");
    }

Explanation:
On the first line, we set a private variable to false.
Using this variable we can check if to call the initialize method on the continuous method.
And the rest is clear as glass.

1 Like

A bit of a formatting error, but you get it. RIGHT.

1 Like

A much better way would be to introduce your own ‘Initialise’ method, probably composed with an interface that you implement in any components that requires it.

As you generate all these game objects you can keep references to them in a collection. Once you’re done, then you can run down the collection and initialise them.

public interface IInitialisable
{
    public void Initialise();
}

//usage
foreach (GameObject go in gameObjectsIMade)
{
    if (go.TryGetComponent(out IInitialisable initialise)
    {
        initialise.Initialise();
    }
}
1 Like