Editor script coroutine/timer/delay...?

I need the ability to create a delay within an Editor script to cleanup some instantiated prefabs X seconds later… the issue I’ve found is that Update() only appears to run when there is an interaction in the Editor and Invoke/Coroutines appear to not work at all…

Is there any way around this? I saw that someone mentioned increasing the transform position by Vector3.zero within OnGUI but again I found that only runs when there’s an interaction :confused:

Hey MSFX

What you want to do is listen to the EditorApplication.update event:

// This doesn't need to be a MonoBehaviour, you can just as easily implement
// this in an editor script.
public class Example : MonoBehaviour
{
    private float m_LastEditorUpdateTime;

    protected virtual void OnEnable()
    {
        #if UNITY_EDITOR
	    m_LastEditorUpdateTime = Time.realtimeSinceStartup;
        EditorApplication.update += OnEditorUpdate;
        #endif
    }

    protected virtual void OnDisable()
    {
        #if UNITY_EDITOR
	    EditorApplication.update -= OnEditorUpdate;
        #endif
    }

    protected virtual void OnEditorUpdate()
    {
        // In here you can check the current realtime, see if a certain
        // amount of time has elapsed, and perform some task.
    }

}

Following answer for anyone need.

There are many ways to delay in editor mode


if you want to keep using low C# version (.Net 3.5 Equivalent) you can use Editor Coroutines Package:
Menu Window > Package Manager > All

Simple code like this:

static void useDelay()
{
     object obj = new object();
     EditorCoroutineUtility.StartCoroutine(IEDelayEditor(), obj);
}

static IEnumerator IEDelayEditor()
{
     Debug.Log("Wait 1 second");
     yield return new EditorWaitForSeconds(1f);
     Debug.Log("After 1 second");
}

If you use high C# version (.Net 4.x Equivalent), you can you Async Await with many advantages

[MenuItem("ExMenu/Use Delay")]
static void UseDelayAsync()
{
     DelayUseAsync();
}

async static void DelayUseAsync ()
{
      Debug.Log("Waiting 1 second...");
      await Task.Delay(1000);
      Debug.Log("After 1 second...");
}

Ah, I hadn’t noticed that event… awesome, thanks! :slight_smile: