[Tips] How to pass data to instantiated Prefab before Awake and OnEnable

I’d like to share this unity trick. Its very often you’d like to instantiate prefab and pass some data to him before Awake() and OnEnable() method invoked on internal scripts. This code just save prefab active state to temporary variable and disable prefab => Instantiate => Invokes beforeAwake => Revert prefab active state => Revert instantiated prefab active state. (at this time Awake and OnEnable will be invoked).

static public T Instantiate<T>(T unityObject, System.Action<T> beforeAwake = null) where T : UnityEngine.Object
    {
        //Find prefab gameObject
        var gameObject = unityObject as GameObject;
        var component = unityObject as Component;

        if (gameObject == null && component != null)
            gameObject = component.gameObject;

        //Save current prefab active state
        var isActive = false;
        if (gameObject != null)
        {
            isActive = gameObject.activeSelf;
            //Deactivate
            gameObject.SetActive(false);
        }

        //Instantiate
        var obj = Object.Instantiate(unityObject) as T;
        if (obj == null)
            throw new Exception("Failed to instantiate Object " + unityObject);

        //This funciton will be executed before awake of any script inside
        if (beforeAwake != null)
            beforeAwake(obj);

        //Revert prefab active state
        if (gameObject != null)
            gameObject.SetActive(isActive);

        //Find instantiated GameObject
        gameObject = obj as GameObject;
        component = obj as Component;

        if (gameObject == null && component != null)
            gameObject = component.gameObject;

        //Set active state to prefab state
        if (gameObject != null)
            gameObject.SetActive(isActive);

        return obj;
    }

I use this trick to make Dependency Injection into instantiated prefab that should be done before Awake, where this dependencies are used.

8 Likes

that was valuable. thank you.

Great function! Only good answer I’ve found.