Search code examples
c#unity-game-enginestack-overflowinfinite-loop

How to delete an object in Unity in ExecuteInEditMode


What I am trying to do

I am trying to have one object with a serialized int that will spawn the number of objects I specify. When I change the number to a lower number, it should obviously delete and destroy the previous ones created.

This is causing an issue, however, do to the way Update works with ExecuteInEditMode, in that it gets executed whenever the scene gets changed, making this much harder.

What I've tried

[ExecuteInEditMode]
public class Floor : MonoBehaviour
{
    [SerializeField] GameObject gameObject;
    [SerializeField] bool shouldDestroy;

    private void Update()
    {
        if (shouldDestroy)
        {
            shouldDestroy = !shouldDestroy;
            gameObject.Destroy();
        }
    }
}

Unreal Engine used this pattern a lot of having a visible bool that turns itself off and behaves more like a button in the editor, which came in handy. This would allow me to press shouldDestroy and destroy the object. Obviously, without the check, it would destroy gameObject, and Update is called again, it will destroy it again and so on.

I thought by added this boolean check, when Update was called again, it wouldn't do anything so the loop would stop, but nope, it continues and gets me an infinite loop.

I've also tried using a Coroutine, but that didn't fix anything.

Is there any way to delete an object in ExecuteInEditMode without causing an infinite loop? Maybe there's a better method than Update that doesn't update when anything in the scene changes?


Solution

  • Try

    GameObject.DestroyImmediate(gameObject);

    in Edit mode: https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html