Unity/Study
[Unity] Coroutine 의 yield return 뒤 함수 확장
Kim2558
2018. 5. 31. 03:09
1. IEnumerator 구현
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using System.Collections; using UnityEngine; public class UseIEnumerator : IEnumerator { public object Current { get { return null; } } public bool MoveNext() { return !Input.GetKey(KeyCode.Space); } public void Reset() { } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System.Collections; using UnityEngine; public class Main : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(CoroutineTest()); } IEnumerator CoroutineTest() { while(true) { yield return new UseIEnumerator(); Debug.Log("Running"); } } } | cs |
2. CustomYieldInstruction 구현
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using UnityEngine; public class UseCustomYieldInstruction : CustomYieldInstruction { public override bool keepWaiting { get { return !Input.GetKey(KeyCode.Space); } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System.Collections; using UnityEngine; public class Main : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(CoroutineTest()); } IEnumerator CoroutineTest() { while(true) { yield return new UseCustomYieldInstruction(); Debug.Log("Running"); } } } | cs |
3. WaitUntil
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System.Collections; using UnityEngine; public class Main : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(CoroutineTest()); } IEnumerator CoroutineTest() { while(true) { yield return new WaitUntil(() => Input.GetKey(KeyCode.Space)); Debug.Log("Running"); } } } | cs |
지금처럼 단순히 스페이스바를 눌렀을 때 멈춘다 정도의 기능을 원한다면 WaitUntil을 사용하는것이 제일 단순하고 깔끔해보인다.
위 코드에서는 yield return 뒤에 new 생성자를 통해 인스턴스화 하고 있는데 미리 캐싱해놓는게 실제 사용에서는 바람직할 것 같다.
IEnumerator > CustomYieldInstruction > WaitUntil 순으로 자유도가 높다.