Created
May 6, 2017 15:19
-
-
Save Q-Bert-Reynolds/eba6ed83862cf73b02dbc12929e4d48c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class CoroutineExample : MonoBehaviour { | |
void Start () { | |
StartCoroutine("YourCoroutine"); | |
} | |
IEnumerator YourCoroutine() { | |
// do something immediately | |
SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>(); | |
spriteRenderer.color = Color.red; | |
// do something after 5 seconds | |
yield return new WaitForSeconds(5f); | |
spriteRenderer.color = Color.red; | |
// do something over the next 3 seconds | |
for (float t = 0; t < 3f; t += Time.deltaTime) { | |
float fraction = t / 3f; | |
spriteRenderer.color = Color.Lerp(Color.red, Color.blue, fraction); | |
yield return new WaitForEndOfFrame(); //infinite loop if this line is missing | |
} | |
// wait for some other coroutine to finish | |
yield return StartCoroutine("SomeOtherCoroutine"); | |
spriteRenderer.color = Color.black; | |
// run coroutine in parallel(ish) | |
StartCoroutine("SomeOtherCoroutine"); | |
spriteRenderer.color = Color.white; | |
} | |
IEnumerator SomeOtherCoroutine() { | |
// does nothing but yield return is required when the return type is IEnumerator | |
yield return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment