Skip to content

Instantly share code, notes, and snippets.

@Sacristan
Forked from benblo/EditorCoroutine.cs
Last active April 13, 2017 03:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sacristan/2190356c8e1dbcf1b2bf623d8d36e583 to your computer and use it in GitHub Desktop.
Save Sacristan/2190356c8e1dbcf1b2bf623d8d36e583 to your computer and use it in GitHub Desktop.
EditorCoroutine: coroutines for Unity editor operations. Usage: EditorCoroutine.start(myIEnumerator)
//Original Author (gracefully borrowed): https://gist.github.com/benblo/10732554
//#define DEBUG_EDITORCOROUTINE
using System.Collections;
using UnityEditor;
namespace Sacristan.EditorExtensions
{
public class EditorCoroutine
{
#region Fields
private readonly IEnumerator routine;
#endregion
#region Constructors
EditorCoroutine(IEnumerator routine)
{
this.routine = routine;
}
#endregion
#region Public Methods
public static EditorCoroutine StartCoroutine(IEnumerator _routine)
{
EditorCoroutine coroutine = new EditorCoroutine(_routine);
coroutine.Start();
return coroutine;
}
#endregion
#region Private Methods
private void Start()
{
#if DEBUG_EDITORCOROUTINE
UnityEngine.Debug.Log("Start");
#endif
EditorApplication.update += Update;
}
private void Stop()
{
#if DEBUG_EDITORCOROUTINE
UnityEngine.Debug.Log("Stop");
#endif
EditorApplication.update -= Update;
}
private void Update()
{
#if DEBUG_EDITORCOROUTINE
UnityEngine.Debug.Log("Update");
#endif
if (!routine.MoveNext()) Stop();
}
#endregion
}
}
using System;
using System.Collections;
using UnityEngine;
using UnityEditor;
using Random = UnityEngine.Random;
namespace Sacristan.EditorExtensions.Test
{
public class TestEditorCoroutine
{
static void testEditorCoroutine()
{
EditorCoroutine.StartCoroutine(testRoutine());
}
static IEnumerator testRoutine()
{
Debug.Log("hello " + DateTime.Now.Ticks);
yield return null;
Debug.Log("done " + DateTime.Now.Ticks);
}
static void testEditorCoroutineWithException()
{
EditorCoroutine.StartCoroutine(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);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment