I got a weird problem with the DestroyImmedeate() function. First off, here’s a version of the script that I reduced to the problematic part:
using UnityEngine;
using UnityEditor;
[ExecuteInEditMode]
public class MyScript : MonoBehaviour {
public MyComponent myComponent;
void Awake() {
myComponent = Instantiate<GameObject>(
Resources.Load<GameObject>("Prefabs/MyComponentPrefab"),
this.transform
)
.GetComponent<MyComponent>();
}
void OnDestroy () {
if (EditorApplication.isPlaying)
{
Destroy(myComponent.gameObject);
}
else
{
DestroyImmediate(myComponent.gameObject); // <- this behaves wrong some times?
}
}
}
The problem occurs when I switch from edit to playmode. So basically, what I expect to happen, is that when the OnDestroy() function gets called, the GameObject attached to the myComponent variable gets removed completely.
Then, Awake() is called and a new instance is created, again, as a child in the hierarchy.
For some reason though, DestroyImmediate(myComponent.gameObject) is called but only the component gets removed. What stays is an GameObject containing all the other components that were attached to it despite MyComponent and it is still listed as a child of MyScript in the hierarchy.
If everything worked the whole GameObject should be gone so what am I missing here?