有时候我们在编辑器开发时候会遇到要在编辑器中开启协同程序的需求,但是我们发现在editor模式下并没有StartCoroutine的实现,那我们就要造个轮子了,首先我们在Editor实现Update函数保证更新,EditorApplication.update += Update;再利用栈堆或者队列储存存放IEnumerator,这保证了是基于队列的方法进行排列请求,下面是实现的源代码: using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices;
publicstatic IEnumerator StartEditorCoroutine(IEnumerator iterator)
{ if (editorCoroutineList == null)
{
// test
editorCoroutineList = new List<EditorCoroutine>();
} if (buffer == null)
{
buffer = new List<IEnumerator>();
} if (editorCoroutineList.Count == 0)
{ EditorApplication.update += Update;
}
// add iterator to buffer first
buffer.Add(iterator);
return iterator;
}
privatestaticbool Find(IEnumerator iterator)
{
// If this iterator is already added
// Then ignore it this time foreach (EditorCoroutine editorCoroutine in editorCoroutineList)
{ if (editorCoroutine.Find(iterator))
{ return true;
}
}
return false;
}
privatestaticvoid Update()
{
// EditorCoroutine execution may append new iterators to buffer
// Therefore we should run EditorCoroutine first
editorCoroutineList.RemoveAll
(
coroutine => { return coroutine.MoveNext() == false; }
);
// If we have iterators in buffer if (buffer.Count > 0)
{ foreach (IEnumerator iterator in buffer)
{
// If this iterators not exists if (!Find(iterator))
{
// Added this as new EditorCoroutine
editorCoroutineList.Add(new EditorCoroutine(iterator));
}
}
// Clear buffer
buffer.Clear();
}
// If we have no running EditorCoroutine
// Stop calling update anymore if (editorCoroutineList.Count == 0)
{ EditorApplication.update -= Update;
}
}
}