Skip to content

Instantly share code, notes, and snippets.

@benblo
Created April 15, 2014 13:26

Revisions

  1. benblo created this gist Apr 15, 2014.
    50 changes: 50 additions & 0 deletions EditorCoroutine.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEditor;
    using UnityEngine;
    using Object = UnityEngine.Object;

    namespace Swing.Editor
    {
    public class EditorCoroutine
    {
    public static EditorCoroutine start( IEnumerator _routine )
    {
    EditorCoroutine coroutine = new EditorCoroutine(_routine);
    coroutine.start();
    return coroutine;
    }

    readonly IEnumerator routine;
    EditorCoroutine( IEnumerator _routine )
    {
    routine = _routine;
    }

    void start()
    {
    //Debug.Log("start");
    EditorApplication.update += update;
    }
    public void stop()
    {
    //Debug.Log("stop");
    EditorApplication.update -= update;
    }

    void update()
    {
    /* NOTE: no need to try/catch MoveNext,
    * if an IEnumerator throws its next iteration returns false.
    * Also, Unity probably catches when calling EditorApplication.update.
    */

    //Debug.Log("update");
    if (!routine.MoveNext())
    {
    stop();
    }
    }
    }
    }
    55 changes: 55 additions & 0 deletions TestEditorCoroutine.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Object = UnityEngine.Object;
    using UnityEditor;
    using Random = UnityEngine.Random;

    namespace Swing.Editor.Test
    {
    public class TestEditorCoroutine
    {
    [MenuItem("Swing/Test/Test Editor Coroutine")]
    static void testEditorCoroutine()
    {
    EditorCoroutine.start(testRoutine());
    }
    static IEnumerator testRoutine()
    {
    Debug.Log("hello " + DateTime.Now.Ticks);
    yield return null;
    Debug.Log("done " + DateTime.Now.Ticks);
    }

    [MenuItem("Swing/Test/Test Editor Coroutine With Exception")]
    static void testEditorCoroutineWithException()
    {
    EditorCoroutine.start(testRoutineWithException());
    }
    static IEnumerator testRoutineWithException()
    {
    Debug.Log("hello " + DateTime.Now.Ticks);
    yield return null;

    for (int i = 0; i < 10; i++)
    {
    testRandomException();
    yield return null;
    }

    Debug.Log("done " + DateTime.Now.Ticks);
    }
    static void testRandomException()
    {
    if (Random.value < 0.3f)
    {
    throw new Exception("ahah! " + DateTime.Now.Ticks);
    }
    else
    {
    Debug.Log("ok " + DateTime.Now.Ticks);
    }
    }
    }
    }