Coroutine

RudinP·2023년 3월 27일
0

Study

목록 보기
6/227

IEnumerator

유니티의 코루틴은 고유 문법

코루틴의 역할

  • 처리간 대기 시간 삽입 가능
  • 여러 처리를 병렬로 처리하도록 해줌

코루틴의 사용 예시

  • Fade In/Out
  • 쯔꾸르 게임 이벤트 발생 시 화면 애니메이션 구현 부분(팀프로젝트 WaitForSomleading)

처리간 대기 시간 삽입 경우

IEnumerator Coroutine(){
	A{}
	yield return new WaitForSeconds(0.01f); // 명시된 대기 시간만큼 대기한다. 이 때, 코드 밖으로 빠져나가 대기한다. 다시 실행될 때는 yield 코드부분에서부터 시작된다.
    B{}
}
void Start(){
	StartCoroutine("Coroutine"); // StartCoroutine(Coroutine());도 동일 
}

여러 처리를 병렬로 처리할 경우 (비동기 방식)

void Start() {
	StartCoroutine("HelloUnity");
    StartCoroutine("HiCSharp");
}
IEnumerator HelloUnity()
{
	Debug.Log("Hello");
    yield return new WaitForSeconds(3f);
    Debug.Log("Unity");
}
IEnumerator HiCSharp()
{
	Debug.Log("Hi");
    yield return new WaitForSeconds(5f);
    Debug.Log("CSharp");
}

Hello
Hi
Unity
CSharp //5초가 걸림(not 8초)
순으로 처리된다. 즉, 병렬 처리가 가능하다.

  • 문자열로 넣을 경우
    • 나중에 임의로 코루틴을 멈출 수 있다.
    • StopCoroutine()
  • 함수형으로 넣을 경우
    • 나중에 임의로 코루틴을 멈출 수 없다.
    • 성능이 더 좋다.
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글