Encapsulate timed events with coroutines in Unity
Creating a separate timer and incrementing it with each Update() step can be useful…sometimes. Certain events that occur in Update() may need to reference the timer’s value directly, in which case it’s just easier to create a timer specifically for that purpose.
But before you decide to create another float timer
, consider that coroutines in Unity can make timed events easier to track and improve your code’s readability.
WaitForEndOfFrame()
If you have a timed event that would otherwise run inside an Update() call, try running a coroutine using,
yield return new WaitForEndOfFrame()
It’s a clean, encapsulated way to run a sequence event outside of Update() while retaining functionality (and using a locally defined timer instead).
Example: Move a GameObject for 5 seconds.
public class CoroutineTest : MonoBehaviour{ public GameObject bob; void Start(){ StartCoroutine( PrintDelayedSequence(bob, 5.0f) ); } IEnumerator PrintDelayedSequence( GameObject gobj, float delay ){ float timer = 0.0f; while (timer < delay){ gobj.transform.position += Vector.right; yield return new WaitForEndOfFrame(); timer += Time.deltaTime; } } }