EditorCoroutines.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEditor;
  4. using System.Collections.Generic;
  5. using System;
  6. using System.Reflection;
  7. namespace marijnz.EditorCoroutines
  8. {
  9. internal class EditorCoroutines
  10. {
  11. internal class EditorCoroutine
  12. {
  13. public ICoroutineYield currentYield = new YieldDefault();
  14. public IEnumerator routine;
  15. public string routineUniqueHash;
  16. public string ownerUniqueHash;
  17. public string MethodName = "";
  18. public int ownerHash;
  19. public string ownerType;
  20. public bool finished = false;
  21. public EditorCoroutine(IEnumerator routine, int ownerHash, string ownerType)
  22. {
  23. this.routine = routine;
  24. this.ownerHash = ownerHash;
  25. this.ownerType = ownerType;
  26. ownerUniqueHash = ownerHash + "_" + ownerType;
  27. if (routine != null)
  28. {
  29. string[] split = routine.ToString().Split('<', '>');
  30. if (split.Length == 3)
  31. {
  32. this.MethodName = split[1];
  33. }
  34. }
  35. routineUniqueHash = ownerHash + "_" + ownerType + "_" + MethodName;
  36. }
  37. public EditorCoroutine(string methodName, int ownerHash, string ownerType)
  38. {
  39. MethodName = methodName;
  40. this.ownerHash = ownerHash;
  41. this.ownerType = ownerType;
  42. ownerUniqueHash = ownerHash + "_" + ownerType;
  43. routineUniqueHash = ownerHash + "_" + ownerType + "_" + MethodName;
  44. }
  45. }
  46. public interface ICoroutineYield
  47. {
  48. bool IsDone(float deltaTime);
  49. }
  50. struct YieldDefault : ICoroutineYield
  51. {
  52. public bool IsDone(float deltaTime)
  53. {
  54. return true;
  55. }
  56. }
  57. struct YieldWaitForSeconds : ICoroutineYield
  58. {
  59. public float timeLeft;
  60. public bool IsDone(float deltaTime)
  61. {
  62. timeLeft -= deltaTime;
  63. return timeLeft < 0;
  64. }
  65. }
  66. struct YieldCustomYieldInstruction : ICoroutineYield
  67. {
  68. public CustomYieldInstruction customYield;
  69. public bool IsDone(float deltaTime)
  70. {
  71. return !customYield.keepWaiting;
  72. }
  73. }
  74. struct YieldWWW : ICoroutineYield
  75. {
  76. public WWW Www;
  77. public bool IsDone(float deltaTime)
  78. {
  79. return Www.isDone;
  80. }
  81. }
  82. struct YieldAsync : ICoroutineYield
  83. {
  84. public AsyncOperation asyncOperation;
  85. public bool IsDone(float deltaTime)
  86. {
  87. return asyncOperation.isDone;
  88. }
  89. }
  90. struct YieldNestedCoroutine : ICoroutineYield
  91. {
  92. public EditorCoroutine coroutine;
  93. public bool IsDone(float deltaTime)
  94. {
  95. return coroutine.finished;
  96. }
  97. }
  98. static EditorCoroutines instance = null;
  99. Dictionary<string, List<EditorCoroutine>> coroutineDict = new Dictionary<string, List<EditorCoroutine>>();
  100. List<List<EditorCoroutine>> tempCoroutineList = new List<List<EditorCoroutine>>();
  101. Dictionary<string, Dictionary<string, EditorCoroutine>> coroutineOwnerDict =
  102. new Dictionary<string, Dictionary<string, EditorCoroutine>>();
  103. DateTime previousTimeSinceStartup;
  104. /// <summary>Starts a coroutine.</summary>
  105. /// <param name="routine">The coroutine to start.</param>
  106. /// <param name="thisReference">Reference to the instance of the class containing the method.</param>
  107. public static EditorCoroutine StartCoroutine(IEnumerator routine, object thisReference)
  108. {
  109. CreateInstanceIfNeeded();
  110. return instance.GoStartCoroutine(routine, thisReference);
  111. }
  112. /// <summary>Starts a coroutine.</summary>
  113. /// <param name="methodName">The name of the coroutine method to start.</param>
  114. /// <param name="thisReference">Reference to the instance of the class containing the method.</param>
  115. public static EditorCoroutine StartCoroutine(string methodName, object thisReference)
  116. {
  117. return StartCoroutine(methodName, null, thisReference);
  118. }
  119. /// <summary>Starts a coroutine.</summary>
  120. /// <param name="methodName">The name of the coroutine method to start.</param>
  121. /// <param name="value">The parameter to pass to the coroutine.</param>
  122. /// <param name="thisReference">Reference to the instance of the class containing the method.</param>
  123. public static EditorCoroutine StartCoroutine(string methodName, object value, object thisReference)
  124. {
  125. MethodInfo methodInfo = thisReference.GetType()
  126. .GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  127. if (methodInfo == null)
  128. {
  129. Debug.LogError("Coroutine '" + methodName + "' couldn't be started, the method doesn't exist!");
  130. }
  131. object returnValue;
  132. if (value == null)
  133. {
  134. returnValue = methodInfo.Invoke(thisReference, null);
  135. }
  136. else
  137. {
  138. returnValue = methodInfo.Invoke(thisReference, new object[] {value});
  139. }
  140. if (returnValue is IEnumerator)
  141. {
  142. CreateInstanceIfNeeded();
  143. return instance.GoStartCoroutine((IEnumerator) returnValue, thisReference);
  144. }
  145. else
  146. {
  147. Debug.LogError("Coroutine '" + methodName + "' couldn't be started, the method doesn't return an IEnumerator!");
  148. }
  149. return null;
  150. }
  151. /// <summary>Stops all coroutines being the routine running on the passed instance.</summary>
  152. /// <param name="routine"> The coroutine to stop.</param>
  153. /// <param name="thisReference">Reference to the instance of the class containing the method.</param>
  154. public static void StopCoroutine(IEnumerator routine, object thisReference)
  155. {
  156. CreateInstanceIfNeeded();
  157. instance.GoStopCoroutine(routine, thisReference);
  158. }
  159. /// <summary>
  160. /// Stops all coroutines named methodName running on the passed instance.</summary>
  161. /// <param name="methodName"> The name of the coroutine method to stop.</param>
  162. /// <param name="thisReference">Reference to the instance of the class containing the method.</param>
  163. public static void StopCoroutine(string methodName, object thisReference)
  164. {
  165. CreateInstanceIfNeeded();
  166. instance.GoStopCoroutine(methodName, thisReference);
  167. }
  168. /// <summary>
  169. /// Stops all coroutines running on the passed instance.</summary>
  170. /// <param name="thisReference">Reference to the instance of the class containing the method.</param>
  171. public static void StopAllCoroutines(object thisReference)
  172. {
  173. CreateInstanceIfNeeded();
  174. instance.GoStopAllCoroutines(thisReference);
  175. }
  176. static void CreateInstanceIfNeeded()
  177. {
  178. if (instance == null)
  179. {
  180. instance = new EditorCoroutines();
  181. instance.Initialize();
  182. }
  183. }
  184. void Initialize()
  185. {
  186. previousTimeSinceStartup = DateTime.Now;
  187. EditorApplication.update += OnUpdate;
  188. }
  189. void GoStopCoroutine(IEnumerator routine, object thisReference)
  190. {
  191. GoStopActualRoutine(CreateCoroutine(routine, thisReference));
  192. }
  193. void GoStopCoroutine(string methodName, object thisReference)
  194. {
  195. GoStopActualRoutine(CreateCoroutineFromString(methodName, thisReference));
  196. }
  197. void GoStopActualRoutine(EditorCoroutine routine)
  198. {
  199. if (coroutineDict.ContainsKey(routine.routineUniqueHash))
  200. {
  201. coroutineOwnerDict[routine.ownerUniqueHash].Remove(routine.routineUniqueHash);
  202. coroutineDict.Remove(routine.routineUniqueHash);
  203. }
  204. }
  205. void GoStopAllCoroutines(object thisReference)
  206. {
  207. EditorCoroutine coroutine = CreateCoroutine(null, thisReference);
  208. if (coroutineOwnerDict.ContainsKey(coroutine.ownerUniqueHash))
  209. {
  210. foreach (var couple in coroutineOwnerDict[coroutine.ownerUniqueHash])
  211. {
  212. coroutineDict.Remove(couple.Value.routineUniqueHash);
  213. }
  214. coroutineOwnerDict.Remove(coroutine.ownerUniqueHash);
  215. }
  216. }
  217. EditorCoroutine GoStartCoroutine(IEnumerator routine, object thisReference)
  218. {
  219. if (routine == null)
  220. {
  221. Debug.LogException(new Exception("IEnumerator is null!"), null);
  222. }
  223. EditorCoroutine coroutine = CreateCoroutine(routine, thisReference);
  224. GoStartCoroutine(coroutine);
  225. return coroutine;
  226. }
  227. void GoStartCoroutine(EditorCoroutine coroutine)
  228. {
  229. if (!coroutineDict.ContainsKey(coroutine.routineUniqueHash))
  230. {
  231. List<EditorCoroutine> newCoroutineList = new List<EditorCoroutine>();
  232. coroutineDict.Add(coroutine.routineUniqueHash, newCoroutineList);
  233. }
  234. coroutineDict[coroutine.routineUniqueHash].Add(coroutine);
  235. if (!coroutineOwnerDict.ContainsKey(coroutine.ownerUniqueHash))
  236. {
  237. Dictionary<string, EditorCoroutine> newCoroutineDict = new Dictionary<string, EditorCoroutine>();
  238. coroutineOwnerDict.Add(coroutine.ownerUniqueHash, newCoroutineDict);
  239. }
  240. // If the method from the same owner has been stored before, it doesn't have to be stored anymore,
  241. // One reference is enough in order for "StopAllCoroutines" to work
  242. if (!coroutineOwnerDict[coroutine.ownerUniqueHash].ContainsKey(coroutine.routineUniqueHash))
  243. {
  244. coroutineOwnerDict[coroutine.ownerUniqueHash].Add(coroutine.routineUniqueHash, coroutine);
  245. }
  246. MoveNext(coroutine);
  247. }
  248. EditorCoroutine CreateCoroutine(IEnumerator routine, object thisReference)
  249. {
  250. return new EditorCoroutine(routine, thisReference.GetHashCode(), thisReference.GetType().ToString());
  251. }
  252. EditorCoroutine CreateCoroutineFromString(string methodName, object thisReference)
  253. {
  254. return new EditorCoroutine(methodName, thisReference.GetHashCode(), thisReference.GetType().ToString());
  255. }
  256. void OnUpdate()
  257. {
  258. float deltaTime = (float) (DateTime.Now.Subtract(previousTimeSinceStartup).TotalMilliseconds / 1000.0f);
  259. previousTimeSinceStartup = DateTime.Now;
  260. if (coroutineDict.Count == 0)
  261. {
  262. return;
  263. }
  264. tempCoroutineList.Clear();
  265. foreach (var pair in coroutineDict)
  266. tempCoroutineList.Add(pair.Value);
  267. for (var i = tempCoroutineList.Count - 1; i >= 0; i--)
  268. {
  269. List<EditorCoroutine> coroutines = tempCoroutineList[i];
  270. for (int j = coroutines.Count - 1; j >= 0; j--)
  271. {
  272. EditorCoroutine coroutine = coroutines[j];
  273. if (!coroutine.currentYield.IsDone(deltaTime))
  274. {
  275. continue;
  276. }
  277. if (!MoveNext(coroutine))
  278. {
  279. coroutines.RemoveAt(j);
  280. coroutine.currentYield = null;
  281. coroutine.finished = true;
  282. }
  283. if (coroutines.Count == 0)
  284. {
  285. coroutineDict.Remove(coroutine.ownerUniqueHash);
  286. }
  287. }
  288. }
  289. }
  290. static bool MoveNext(EditorCoroutine coroutine)
  291. {
  292. if (coroutine.routine.MoveNext())
  293. {
  294. return Process(coroutine);
  295. }
  296. return false;
  297. }
  298. // returns false if no next, returns true if OK
  299. static bool Process(EditorCoroutine coroutine)
  300. {
  301. object current = coroutine.routine.Current;
  302. if (current == null)
  303. {
  304. coroutine.currentYield = new YieldDefault();
  305. }
  306. else if (current is WaitForSeconds)
  307. {
  308. float seconds = float.Parse(GetInstanceField(typeof(WaitForSeconds), current, "m_Seconds").ToString());
  309. coroutine.currentYield = new YieldWaitForSeconds() {timeLeft = seconds};
  310. }
  311. else if (current is CustomYieldInstruction)
  312. {
  313. coroutine.currentYield = new YieldCustomYieldInstruction()
  314. {
  315. customYield = current as CustomYieldInstruction
  316. };
  317. }
  318. else if (current is WWW)
  319. {
  320. coroutine.currentYield = new YieldWWW {Www = (WWW) current};
  321. }
  322. else if (current is WaitForFixedUpdate || current is WaitForEndOfFrame)
  323. {
  324. coroutine.currentYield = new YieldDefault();
  325. }
  326. else if (current is AsyncOperation)
  327. {
  328. coroutine.currentYield = new YieldAsync {asyncOperation = (AsyncOperation) current};
  329. }
  330. else if (current is EditorCoroutine)
  331. {
  332. coroutine.currentYield = new YieldNestedCoroutine { coroutine= (EditorCoroutine) current};
  333. }
  334. else
  335. {
  336. Debug.LogException(
  337. new Exception("<" + coroutine.MethodName + "> yielded an unknown or unsupported type! (" + current.GetType() + ")"),
  338. null);
  339. coroutine.currentYield = new YieldDefault();
  340. }
  341. return true;
  342. }
  343. static object GetInstanceField(Type type, object instance, string fieldName)
  344. {
  345. BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
  346. FieldInfo field = type.GetField(fieldName, bindFlags);
  347. return field.GetValue(instance);
  348. }
  349. }
  350. }