Tuesday 1 November 2022

Unity Coroutine

Let's say that you want to run some asynchronous task after a timer of some sort, then the StartCoroutine method is your friend, with a very set it and forget it approach.

    // Start is called before the first frame update
    void Start()
        StartCoroutine("doSomethingAfter5seconds", "Say hi");

     IEnumerator doSomethingAfter3seconds(){
        yield return new WaitForSeconds(3);
        Debug.Log("it's been 3 seconds");

      IEnumerator doSomethingAfter5seconds(object value){
        yield return new WaitForSeconds(5);
        Debug.Log($"it's been 5 seconds, {value}");

And that's all there is to it, there's also controller function. that will let you stop your coroutine or stop all coroutines.