저번 시간에
yield return null;
yield return new WaitForSeconds();
두가지 대기 조건을 알아봤습니다.
이번에 나머지 대기 조건을 알아보도록 하겠습니다.
유니티 문서를 보면 코루틴이 언제 실행되는지 알 수 있습니다.

지난시간에 대기 조건중 null과 비슷하게 FixedUpdate 이후에 실행되며,
WaitForFixedUpdate는 Time.fixedDeltaTime과 똑같은 시간을 대기합니다.
(Time.fixedDeltaTime = 지난 FixedUpdate 프레임이 완료되는데까지 걸린 시간
{기본 설정시 대략 0.02초})
따라서 이 대기 조건을 무한 루프에 사용하면 FixedUpdate의 서브 루틴을 만들 수 있습니다.
public class 코루틴 : MonoBehaviour
{
WaitForFixedUpdate waitForFixedUpdate = new WaitForFixedUpdate();
//루프에서 사용시 캐싱하여 사용하는 편이 좋습니다.
IEnumerator MyCo()
{
while (true)
{
//...
//FixedUpdate 서브 루틴에 실행 할 코드
yield return waitForFixedUpdate;
}
}
}
FixedUpdate(), Update(), LateUpdate() 이벤트가 모두 실행되고 화면에 렌더링이 끝난 이후에 호출 됩니다.
하나의 프레임의 맨 마지막에 처리해야할 작업이 있을때 사용합니다.
public class 코루틴 : MonoBehaviour
{
WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame();
//루프에서 사용시 캐싱하여 사용하는 편이 좋습니다.
IEnumerator MyCo()
{
while (true)
{
yield return WaitForEndOfFrame;
//...
// 프레임 맨 마지막에 실행할 코드
}
}
}
코루틴 함수 안에서
yeild return 의 대기 조건에 StartCoroutine() 함수로 코루틴을 실행시킬 수 있습니다.
이것을 활용하여 코루틴1 -> 코루틴2 -> 코루틴3 차례대로 실행 시킨다면
코루틴을 콜백함수처럼 사용할 수 있습니다.
public class 코루틴 : MonoBehaviour
{
IEnumerator Enumerator;
void Start()
{
Enumerator = ChaineCo();
StartCoroutine(Enumerator); //체인 코루틴 실행
}
IEnumerator ChaineCo()
{
yield return StartCoroutine(yeild02()); //첫 번째 코루틴이 끝날때까지 대기
yield return StartCoroutine(yeild03()); //두 번째 코루틴이 끝날때까지 대기
}
IEnumerator yeild02()
{
float value02 = 0;
while (true)
{
value02 += Time.deltaTime;
if (value02 >= 2)
{
value02 = 3f;
break;
}
yield return null;
}
Debug.Log("yeild02 End");
}
IEnumerator yeild03()
{
float value03 = 0;
while (true)
{
value03 += Time.deltaTime;
if (value03 >= 3)
{
value03 = 3f;
break;
}
yield return null;
}
Debug.Log("yeild03 End");
}
}
WaitUntil은 조건이 만족될때까지 대기 하다가
조건이 true가 됐을때 코루틴으로 되돌아 옵니다.
public class 코루틴 : MonoBehaviour
{
IEnumerator Enumerator;
[SerializeField] float Speed;
void Start()
{
Enumerator = TestCo();
StartCoroutine(Enumerator);
Speed = 0;
}
IEnumerator TestCo()
{
//스피드가 5를 넘어가는 시점까지 대기합니다.
yield return new WaitUntil(() => Speed > 5f);
Debug.Log("실행");
}
}
반대로 WaitWhile은 조건이 false가 될때까지 대기하다가
코루틴으로 되돌아옵니다.
public class 코루틴 : MonoBehaviour
{
IEnumerator Enumerator;
[SerializeField] float Speed;
void Start()
{
Enumerator = TestCo();
StartCoroutine(Enumerator);
Speed = 0;
}
IEnumerator TestCo()
{
//스피드가 5 아래로 내려오는 시점까지 대기합니다.
yield return new WaitWhile(() => Speed < 5f); //부호가 반대입니다
Debug.Log("실행");
}
}