Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class CoroutineExample : MonoBehaviour
- {
- /*
- IEnumerator Start()
- { //start can be used as an IEnumerator, unlike awake
- }
- */
- int a = 0;
- void Start()
- {
- Foo(2); //won't execute because you need to call it with StartCoroutine unless you're already in an IEnumerator
- Print("beginning of start(): should be 0");
- StartCoroutine(Foo(2));
- Print("end of start(): should be 0");
- }
- IEnumerator Foo(int seconds)
- {
- Print("beginning of Foo(): should be 0");
- yield return new WaitForSeconds(seconds); //waitforseconds is builtin unity command
- Print("we wait for the above command: should be "+seconds);
- yield return Bar(seconds * 2);
- }
- IEnumerator Bar(int seconds)
- {
- string note;
- note = "beginning of Bar(): this happens after the WaitForSeconds in Foo";
- Print(note);
- note = "starting IEnumerator inside IEnumerator with yield return: ok, and it waits";
- yield return PrintNoteAndWait1Second(note);
- note = "starting IEnumerator inside IEnumerator: ok, but doesn't wait";
- PrintNoteAndWait1Second(note);
- note = "starting IEnumerator inside IEnumerator with StartCoroutine: ok, but doesn't wait";
- StartCoroutine(PrintNoteAndWait1Second(note));
- Coroutine coroutine = PrintNoteAndWait1Second("you can hold a reference to a couroutine");
- }
- IEnumerator PrintNoteAndWait1Second(string note)
- {
- Print(note);
- yield return new WaitForSeconds(1);
- }
- void Print(string note)
- {
- Debug.Log(String.Format("a: {0} @ {1}\n\t>{2}", a, Time.time, note));
- a++;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment