Search Unity

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

Discussion in 'Community Learning & Teaching' started by PrefabEvolution, Jul 31, 2014.

  1. PrefabEvolution

    PrefabEvolution

    Joined:
    Mar 27, 2014
    Posts:
    225
    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).

    Code (csharp):
    1.  
    2. static public T Instantiate<T>(T unityObject, System.Action<T> beforeAwake = null) where T : UnityEngine.Object
    3.     {
    4.         //Find prefab gameObject
    5.         var gameObject = unityObject as GameObject;
    6.         var component = unityObject as Component;
    7.  
    8.         if (gameObject == null && component != null)
    9.             gameObject = component.gameObject;
    10.  
    11.         //Save current prefab active state
    12.         var isActive = false;
    13.         if (gameObject != null)
    14.         {
    15.             isActive = gameObject.activeSelf;
    16.             //Deactivate
    17.             gameObject.SetActive(false);
    18.         }
    19.  
    20.         //Instantiate
    21.         var obj = Object.Instantiate(unityObject) as T;
    22.         if (obj == null)
    23.             throw new Exception("Failed to instantiate Object " + unityObject);
    24.  
    25.         //This funciton will be executed before awake of any script inside
    26.         if (beforeAwake != null)
    27.             beforeAwake(obj);
    28.  
    29.         //Revert prefab active state
    30.         if (gameObject != null)
    31.             gameObject.SetActive(isActive);
    32.  
    33.         //Find instantiated GameObject
    34.         gameObject = obj as GameObject;
    35.         component = obj as Component;
    36.  
    37.         if (gameObject == null && component != null)
    38.             gameObject = component.gameObject;
    39.  
    40.         //Set active state to prefab state
    41.         if (gameObject != null)
    42.             gameObject.SetActive(isActive);
    43.  
    44.         return obj;
    45.     }
    46.  
    I use this trick to make Dependency Injection into instantiated prefab that should be done before Awake, where this dependencies are used.
     
    Last edited: Jul 31, 2014
  2. forcepusher

    forcepusher

    Joined:
    Jun 25, 2012
    Posts:
    227
    that was valuable. thank you.
     
  3. Seforius

    Seforius

    Joined:
    Jun 25, 2022
    Posts:
    10
    Great function! Only good answer I've found.