Coroutine과 Yield return

2019. 3. 18. 10:24Unity Engine/Script

Coroutine과 Yield return


유니티에서는 작업을 쉽게 분할 처리 하기위해 코루틴이라는 녀석을 제공한다.

코루틴은 메인쓰레드를 비동기식으로 할당하여 특정 작업을 처리하며 그 특성 때문에 몇 가지 반환 방법이 존재한다.


종류는 아래와 같다.


yield return null – the coroutine executes the next time that it is eligible

yield return new WaitForEndOfFrame – the coroutine executes on the frame, after all of the rendering and GUI is complete

yield return new WaitForFixedUpdate – causes this coroutine to execute at the next physics step, after all physics is calculated

yield return new WaitForSeconds – causes the coroutine not to execute for a given game time period

yield return new WWW – waits for a web request to complete (resumes as if WaitForSeconds or null)

yield return Another coroutine – in which case the new coroutine will run to completion before the yielder is resumed


이 중 new 구문이 붙은 wait 종류는 heap을 사용하여 생성되는데, 코루틴 자체가 특정 작업을 반복할때 사용하는 경우가 많아 반복적으로 heap을 사용하게 되며 이로인해 gc문제가 발생하기 쉽다.


그래서 코루틴을 반환할때 wait 종류를 쓸 경우 캐싱하여 쓰는게 좋다.


Static 형태로 클래스를 구성하고 Yield Wait 형태의 반환형을 미리 만들어 둔다.

WaitForSeconds의 경우 들어오는 파라미터에 따라 Dictionary 자료구조체에 쌓아두고 반환



기존의 yield return 을 미리 캐싱된 값으로 대체한다.



스크립트 파일 : Yields.cs