Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Object created in CustomEditor is leaked into scene when play is pressed

Discussion in 'Editor & General Support' started by paulrts, Feb 11, 2019.

  1. paulrts

    paulrts

    Joined:
    Jan 4, 2018
    Posts:
    3
    I'm attempting to instance an object when a custom editor is enabled, and destroy that object when custom editor is disabled.

    However, if you press play while custom editor is enabled, the created object does not get destroyed. It remains in the scene after you stop playing. OnDisable is called just before play starts, so it seems like a bug that the object is leaked into my scene.

    Gif demonstration of issue: https://i.imgur.com/EZOXOmx.gif

    Minimal project reproducing the issue: https://github.com/paulmriordan/unity-custom-editor-instance-disable-bug

    Steps to reproduce:
    • Select object with CreateOnClickInScene
    • Note object is created in scene
    • Start playing in editor
    • Stop playing in editor
    Outcome:
    • Created object remains in the scene
    Expected behaviour:
    • Created object should have been destroyed and no longer in scene

    Using Unity 2018.3.0f2

    Script:
    Code (CSharp):
    1. public class CreateOnClickInScene : MonoBehaviour
    2. {
    3.      public GameObject CreatedObject;
    4. }
    5. #if UNITY_EDITOR
    6. [CustomEditor(typeof(CreateOnClickInScene))]
    7. public class CreateOnClickInSceneEditor : Editor
    8. {
    9.      private CreateOnClickInScene Target { get { return (CreateOnClickInScene)target; } }
    10.      private void OnEnable()
    11.      {
    12.          if (!Application.isPlaying)
    13.          {
    14.              Target.CreatedObject = new GameObject("Editor only object");
    15.          }
    16.      }
    17.      private void OnDisable()
    18.      {
    19.          DestroyImmediate(Target.CreatedObject);
    20.          Target.CreatedObject = null;
    21.      }
    22. }
    Anyone know if this is an open bug, or is there alternative way to do this?
     
    Last edited: Feb 12, 2019