teleias

Unity Coroutines

Jun 10th, 2019
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class CoroutineExample : MonoBehaviour
  4. {
  5.     /*
  6.     IEnumerator Start()
  7.     {   //start can be used as an IEnumerator, unlike awake
  8.     }
  9.     */
  10.     int a = 0;
  11.     void Start()
  12.     {
  13.         Foo(2); //won't execute because you need to call it with StartCoroutine unless you're already in an IEnumerator
  14.  
  15.         Print("beginning of start(): should be 0");
  16.         StartCoroutine(Foo(2));
  17.         Print("end of start(): should be 0");
  18.     }
  19.     IEnumerator Foo(int seconds)
  20.     {
  21.         Print("beginning of Foo(): should be 0");
  22.         yield return new WaitForSeconds(seconds); //waitforseconds is builtin unity command
  23.         Print("we wait for the above command: should be "+seconds);
  24.  
  25.         yield return Bar(seconds * 2);
  26.     }
  27.     IEnumerator Bar(int seconds)
  28.     {
  29.         string note;
  30.  
  31.         note = "beginning of Bar(): this happens after the WaitForSeconds in Foo";
  32.         Print(note);
  33.  
  34.         note = "starting IEnumerator inside IEnumerator with yield return: ok, and it waits";
  35.         yield return PrintNoteAndWait1Second(note);
  36.  
  37.         note = "starting IEnumerator inside IEnumerator: ok, but doesn't wait";
  38.         PrintNoteAndWait1Second(note);
  39.  
  40.         note = "starting IEnumerator inside IEnumerator with StartCoroutine: ok, but doesn't wait";
  41.         StartCoroutine(PrintNoteAndWait1Second(note));
  42.        
  43.  
  44.         Coroutine coroutine = PrintNoteAndWait1Second("you can hold a reference to a couroutine");
  45.     }
  46.     IEnumerator PrintNoteAndWait1Second(string note)
  47.     {
  48.         Print(note);
  49.         yield return new WaitForSeconds(1);
  50.     }
  51.  
  52.     void Print(string note)
  53.     {
  54.         Debug.Log(String.Format("a: {0} @ {1}\n\t>{2}", a, Time.time, note));
  55.         a++;
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment