[Unity] understand the principle of coroutine. 1. Implement your own WaitForSeconds and waitforseconds.
The effect that coroutine can achieve is to execute the code that needs to be executed at the specified time point. The function for starting a coroutine in Unity is StartCoroutine, and the delayed classes provided are as follows:
New WaitForEndOfFrame; // wait for a frame new WaitForFixedUpdate; // wait for a FixedUpdate (fixed interval) new WaitForSeconds; // wait for X seconds new WWW; // wait for external resources to load
This article explores the WaitForSeconds implementation. Because in the development process, it is often the case that the system can continue to run after a timeout or meets certain conditions. The system provides WaitForSeconds, at this time, there are two solutions: one is to use StopCoroutine to stop the coroutine, but for Unity, this behavior will cause a lot of overhead, so you can use WaitForSeconds to override it, make it meet our requirements. The implementation of WaitForSeconds is as follows:
/// <Summary> /// task extension /// </summary> static class CTaskExtend {static public IEnumerator WaitForSeconds (float second) {DateTime init_dt = DateTime. now; TimeSpan time; while (true) {time = DateTime. now-init_dt; if (time. totalSeconds <= second) {yield return null;} else {break ;}}}}
The calling method is similar to that of Unity:
yield return CTaskExtend.WaitForSeconds(delayTime);
It seems to be very simple, but it is also very simple, so if you encounter the situation mentioned earlier (timeout or continue running if it meets certain conditions), what changes need to be made here? As follows:
/// <Summary> /// task extension /// </summary> static class CTaskExtend {public delegate bool CondDelegate (); static public IEnumerator WaitForSeconds (float second, condDelegate cond = null) {DateTime init_dt = DateTime. now; TimeSpan time; while (true) {time = DateTime. now-init_dt; if (time. totalSeconds <= second &&! Cond () {yield return null;} else {break ;}}}}
When a callback function is added, the system checks whether the function is set to true. If the callback function is set to true, the system stops waiting.