Getting around deferred Awake call from SetActive

Here’s a common pattern I use. Instead of using a prefab to instantiate which can be a problem I store a inactive GameObject in the scene and instantiate it and set it active.

Like this:

var elem = Instantiate(prefab);
elem.gameObject.SetActive(true);
elem.Setup(info);

The problem is that when you change something to SetActive it doesn’t call Awake right away. So in the above case Setup is called before Awake is called on elem. If I used a prefab to Instantiate then Awake is called before Setup. I’m curious why it’s this way if Awake is to be used like a constructors then Awake should be called immediately. The solution here is to move initialization code into the Setup function, or delay a Setup call until Awake is called, both not ideal.

Make sure all the parent gameobjects of this gameobject are active, or setting it to Active won’t actually make it active in the scene.

Here is why: Game MUST have a deterministic execution order. If Awake is called at the same time during execution, predictably, it is the right architecture. The patter you want is:

    elem = Instantiate(prefab).GetComponent();
    elem.Configure(info)
    ...
    class Elem:
    void Configure(ElemConfig elemConfig)
    {
        this.elemConfig = elemConfig;
    }
    void Awake()
    {
    // consume the configuration here, when you awaken.
    }