- Home /
Adding a child via code in edit mode won't work for prefab instance
The following MonoBehaviour has [ExecuteAlways] attribute and generates a child object when enabled in edit mode.
If I disable/enable it, the log shows the correct generated object. But when I enter play mode, the log shows null : generated object has been destroyed and I don't know why nor when. I've tested with an object manually created in editor (givenInEditor) and this one is correctly preserved when I enter playmode.
The problem occurs only if the component is on a prefab instance. On a standalone gameobject, everything is fine. It was also working on all 2017 versions.
[ExecuteAlways]
public class Generator : MonoBehaviour {
public GameObject generatedInEditor;
public GameObject givenInEditor;
private void OnEnable() {
string AppMode = Application.isPlaying ? "Playing" : "In editor";
Debug.Log($"{AppMode} OnEnable {generatedInEditor} {givenInEditor}");
generatedInEditor = new GameObject("generated");
generatedInEditor.transform.parent = transform;
}
}
Generating gameobjects via code during edit time is a pretty common need for procedural generation, so how can we keep references of those objets now? Is that a bug in Unity new prefab system?