Editor Update

Unity’s coroutines don’t run in the editor when the app is not playing, but MEC coroutines can.

Editor coroutines are generally used to give the developer a preview of an effect before the game runs, or to perform update or networking sync tasks that need to be done before the actual app is compiled. Editor coroutines will all be destroyed when the user hits the play button, and will not run while in play mode. Time.time and Time.deltaTime will not work while in editor mode, instead you should use Timing.LocalTime and Timing.DeltaTime.

Be conservative when using editor coroutines: An infinite loop or a very processor intensive function here can destroy your entire project. Always make sure to have a backup of your project available whenever you mess with these. Also keep in mind that any changes you make to an object in your scene in the editor will change the initial state of that object when you run or compile the app. For example, you could make an editor coroutine that made your character wink at the developer before play mode, but this would have the side effect of making the character randomly start mid-wink occasionally when they started or compiled the app.

In order to run in the editor, set the Segment to EditorUpdate or EditorSlowUpdate. Make sure your class has the [ExecuteInEditMode] tag attached, and then use them normally. Here is an example:

using UnityEngine;
using System.Collections.Generic;
using MEC;

[ExecuteInEditMode]
public class EditorTesting : MonoBehaviour 
{

    void OnEnable()
    {
        Timing.RunCoroutine(_RunOverAndOver(), Segment.EditorUpdate);
    }

    IEnumerator<float> _RunOverAndOver()
    {
        while(true)
        {
            if(!enabled)
                yield break;

            Timing.RunCoroutine(_MoveThisObject(), Segment.EditorUpdate);

            yield return Timing.WaitForSeconds(1f);
        }
    }
        

    IEnumerator<float> _MoveThisObject()
    {
        double startTime = Timing.LocalTime;
        Vector3 direction = Random.onUnitSphere;

        while(Timing.LocalTime - startTime < 7d)
        {
            Vector3 tmp = transform.position;
            tmp += direction * Timing.DeltaTime;
            transform.position = tmp;

            yield return 0f;
        }
    }
}