UNITY/Script

[UNITY C#] 코루틴(Coroutine) 간단 정리

HYEOKJUN 2022. 6. 19. 14:00
반응형

https://docs.unity3d.com/kr/2021.3/Manual/Coroutines.html

코루틴 - Unity 매뉴얼

코루틴을 사용하면 작업을 다수의 프레임에 분산할 수 있습니다. Unity에서 코루틴은 실행을 일시 정지하고 제어를 Unity에 반환하지만 중단한 부분에서 다음 프레임을 계속할 수 있는 메서드입니

docs.unity3d.com


코루틴 (Coroutine)

코루틴각 프레임 시퀸스에 대해서 명령을 처리해야 하는 경우에 사용하는 작업입니다.


void Fade() {
	SpriteRenderer spriteRenderer;
    
	for(float a = 1f; a >= 0f; a -= 0.05f) {
		Color color = spriteRenderer.color;
		color.a = a;
		spriteRenderer.color = color;
	}
}

일반적으로 업데이트를 처리하는 함수를 호출하면 함수가 한 번에 실행되어 spriteRenderer.color의 알파 값은 한 번에 0이 되는 것처럼 보입니다. 이러한 경우에 Coroutine을 이용합니다.

IEnumerator Fade() {
	SpriteRenderer spriteRenderer;
    
	for(float a = 1f; a >= 0f; a -= 0.05f) {
		Color color = spriteRenderer.color;
		color.a = a;
		spriteRenderer.color = color;
		
		yield return null;
	}
}

다음과 같이 IEnumerator를 반환하는 함수를 작성하여

StartCoroutine(Fade());

다음과 같이 호출하면 프레임마다 알파 값이 1에서 0까지 업데이트되는 것처럼 보입니다.


Coroutine 객체

코루틴은 객체이므로 캐싱할 수 있습니다.

Coroutine coroutine;

또한 코루틴이 중복 실행되는 것을 막기위해서 다음과 같이 처리할 수 있습니다.

if(coroutine != null) {
	StopCoroutine(coroutine);
}
coroutine = StartCoroutine(IEnumerator함수);

다음 코드는 coroutine 실행중에 새로운 Coroutine 실행 요청 시에 기존 coroutine을 중단하고 새로운 Coroutine을 실행합니다.


StartCoroutine(c)

코루틴을 실행합니다.

StartCoroutine(코루틴)
StartCoroutine(IEnumerator함수)
StartCoroutine("IEnumerator함수") // 권장하지 않는 방식입니다.

StopCoroutine(c)

코루틴을 종료합니다.

StopCoroutine(코루틴)
StopCoroutine(IEnumerator함수)
StopCoroutine("IEnumerator함수") // 권장하지 않는 방식입니다.

yield 키워드 활용

IEnumerator 함수에서 yield 키워드코드 진행을 지연시킬 때 사용합니다.


yield break

IEnumerator 함수를 빠져나갑니다.

(일반 함수의 return과 같습니다.)

yield break;

IEnumerator Counting() {
	for(int n = 1; n <= 100; n++) {
		if(n <= 10) {
			Debug.Log(n);
		} else {
			yield break;
		}
	}
}

다음과 같은 Coroutine을 실행하면 1~10까지 출력하고 n이 11이 되면 yield break에 의해서 함수를 빠져나갑니다.


yield return null

한 프레임 동안 지연시킵니다.

yield return null;

IEnumerator Fade() {
	SpriteRenderer spriteRenderer;
    
	for(float a = 1f; a >= 0f; a -= 0.05f) {
		Color color = spriteRenderer.color;
		color.a = a;
		spriteRenderer.color = color;
		
		yield return null;
	}
}

다음과 같은 Coroutine을 실행하면 yield return null에서 한 프레임 지연되어 알파 값이 1에서 0까지 자연스럽게 감소하는 것처럼 보이게 됩니다.


yield return new WaitForSeconds(t)

WaitForSeconds 객체를 이용하여 지정한 시간만큼 지연시킵니다.

(WaitForSeconds는 객체이기 때문에 반복되어 사용하면 상당한 메모리를 차지합니다. 따라서 캐싱하여 사용하는 것이 좋습니다.)

yield return new WaitForSeconds(실수값);

캐싱하여 사용할 때에는 다음과 같이 사용합니다.

WaitForSeconds wfs = new WaitForSeconds(1f);

yield return wfs;

IEnumerator Counting() {
	for(int n = 1; n <= 100; n++) {
		Debug.Log(n);
		
		yield return new WaitForSeconds(1f);
	}
}

다음과 같은 Coroutine을 실행하면 yield return new WaifForSeconds(1f)에서 1초간 지연되어 100초간 카운트를 하는 것처럼 보입니다.

반응형