코루틴이란?
코루틴은 함수 실행중, 중간에 빠져나가고 다른 작업을하다가 다시 중단된 시점부터 이어서 실행하고를 가능하게 해주는 함수를 의미합니다.
그리고 코루틴의 실행은 어느 스레드에서든 가능합니다.(thread-safe를 의미하지는 않음.)
(A쓰레드에서 코루틴을 생성하고 실행하다가 중단하고, B스레드에서 다시 실행하더라도 코루틴은 중단 지점으로부터 정상적으로 재개된다는 것입니다.)
C#의 코루틴
C#자체가 코루틴을 지원하고 있습니다.
class CoroutineTest : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 1;
yield return 2;
yield return 3;
}
}
void Init()
{
CoroutineTest test = new CoroutineTest();
foreach(int t in test)
{
Debug.Log(t);
}
}
//Init()실행시 출력 결과:
//1
//2
//3
class Program
{
public IEnumerator Coroutine()
{
int i = 0;
Console.WriteLine($"Coroutine {++i}");
yield return null;
Console.WriteLine($"Coroutine {++i}");
yield return null;
Console.WriteLine($"Coroutine {++i}");
yield return null;
}
static void Main(string[] args)
{
Program program = new Program();
IEnumerator coroutine = program.Coroutine();
Console.WriteLine("Main 1");
coroutine.MoveNext();
Console.WriteLine("Main 2");
coroutine.MoveNext();
Console.WriteLine("Main 3");
coroutine.MoveNext();
}
}
// OUTPUT :
// Main 1
// Coroutine 1
// Main 2
// Coroutine 2
// Main 3
// Coroutine 3
위와같이 사용 가능합니다.
IEnumerator와 yield를 이용하는 것입니다.
IEnumerator 객체에 MoveNext()를 사용해서 다음 yield return을 실행 가능해집니다.
void Start()
{
IEnumerator enumerator = SomeNumbers();
Debug.Log("=====================================");
// MoveNext()에서 실제로 SomeNumbers()가 실행됩니다.
// 처음에는 "yield return 3;" 까지만 실행됩니다.
while (enumerator.MoveNext())
{
object result = enumerator.Current;
Debug.Log("Number: " + result);
}
}
IEnumerator SomeNumbers()
{
Debug.Log("yield return 1");
yield return 3;
Debug.Log("yield return 2");
yield return 5;
Debug.Log("yield return 3");
yield return 8;
// 이후에는 함수의 끝을 만나게 되므로 더이상 yield(양보)가 일어나지 않습니다.
}
yeid break;
//코루틴을 임의로 종료시키고 싶을때 사용
유니티에서 코루틴
private Coroutine co; //전역변수로 코루틴 변수 선언
void Init()
{
co = StartCoroutine("CoExploadAfterSeconds", 4.0f);
StartCoroutine("CoStopExplode", 2.0f);
}
IEnumerator CoStopExplode(float seconds)
{
Debug.Log("Stop Enter");
yield return new WaitForSeconds(seconds);
Debug.Log("Stop Execute!!!!");
if (co != null)
{
StopCoroutine(co);
co = null;
}
}
IEnumerator CoExploadAfterSeconds(float seconds)
{
Debug.Log("Explode Enter");
yield return new WaitForSeconds(seconds);
Debug.Log("Explode Execute!!!!");
}
유니티에선 WaitForSeconds()를 활용하여 일정시간동안 코루틴함수를 중지시킬 수 있습니다.
StartCoroutine("코루틴함수명",인자) 를 통해서 코루틴함수를 실행 시킬 수 있으며,
StopCoroutine("코루틴함수명") 또는 위처럼 저장해놓은 co변수를 넣어서도 가능.
위 예시에서는 CoExploadAfterSeconds()를 통해서 Explode Enter를 먼저 출력한 후 4초 후에 Explode Execute 를 출력할 예정이었지만 CoStopExplode에서 2초만 기다리고 StopCoroutine(co)를 해줬기 때문에 Explode Excute!!!는 출력되지 않는 것을 확인할 수 있습니다.
위처럼 유니티에서는 함수의 실행 및 중단을 비동기적으로 관리하기 위해서 주로 사용됩니다.
'유니티' 카테고리의 다른 글
[Unity] 애니메이션 이벤트 (0) | 2023.02.18 |
---|---|
[Unity] Json을 이용한 데이터 관리 (0) | 2023.02.03 |
[Unity] 애니메이션 및 행동 관리하기(with 스테이트 패턴) (0) | 2023.01.30 |
[Unity] 애니메이션 기초(스테이트 머신) 및 파라미터 설정 (0) | 2023.01.28 |
[Unity] Input System을 스크립트에서 사용하는법 (0) | 2023.01.25 |