- Home /
 
Instantiating a prefab in the editor is orphaning the children of the prefabs
I have a script I wrote that I am attaching to an empty game object. This script instantiates a prefab that is dropped on it's public GameObject "instantiateObj" variable. I set the Hideflags of DontSaveInEditor and DontSaveInBuild on this instantiated game object.
The goal is to have a scene that I can see in the editor and when running the game that instantiates a prefab each time. This way, if we modify the prefab, it will always contain those changes, and we can nested prefabs.
It's almost working perfectly, but I made two test prefabs, one is made from a regular Unity UI text object, this works fine. The other is a prefab made from a regular Unity UI button, which has a child item that is a Text. When I go from editor mode to play mode, that text is dumped to the root level of my scene when his parent is cleaned up.
When I go from Play mode back to Editor mode, everything cleans up fine. Is there a difference in the way a scene gets cleaned up in the Editor versus Play mode?
 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;
 
 #if UNITY_EDITOR
 using UnityEditor;
 using UnityEditor.Callbacks;
 #endif
 
 [ExecuteInEditMode]
 public class prefabInstantiator : MonoBehaviour {
     public GameObject itemToInstantiate;
     
     GameObject instantiatedObj = null;
 
     void Awake () {
         HideFlags ourFlags = (HideFlags.DontSaveInEditor | HideFlags.DontSaveInBuild);
         
         if(itemToInstantiate != null && instantiatedObj == null) 
         {
             instantiatedObj = (GameObject) Instantiate(itemToInstantiate, transform.position, transform.rotation);
             
             instantiatedObj.transform.SetParent(transform);
             instantiatedObj.transform.localScale = Vector3.one;
             instantiatedObj.hideFlags = ourFlags;
         }
     }
 }
 
              Your answer