Search Unity

  1. Unity 2019.1 beta is now available.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. We're looking for insight from anyone who has experience with game testing to help us better Unity. Take our survey here. If chosen to participate you'll be entered into a sweepstake to win an Amazon gift card.
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Unity 2018.3 is now released.
    Dismiss Notice
  6. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    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


    Jan 4, 2018
    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:

    Minimal project reproducing the issue:

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

    Using Unity 2018.3.0f2

    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