Unity
Coroutine(코루틴)
gcreators
2024. 9. 30. 17:46
Coroutine
유니티에서 비동기적인 작업을 처리 할 때 사용하는 메서드 입니다
가장 큰 특징으로는 일반적인 함수와 다르게 코루틴은 실행중이던 함수를 잠시 중지했다가 나중에 원할 때 다시 시작 할 수 있습니다.
시간 지연이 필요한 작업들에 아주 유용하게 쓰입니다
public class CoroutineExample : MonoBehaviour
{
private Coroutine aCoroutine = null; //코루틴 변수 선언
private WaitForSeconds wait1Sec = new WaitForSeconds(1f); //WaitForSeconds는 IEnumerator를 상속받아서 만들어진 클래스이다.
//1.Coroutine 동작 조건 : MonoBehaviour필수, gameobject가 없거나 script가 꺼져있으면 안돌아감
//코루틴(Coroutine)
private void Start()
{
StartCoroutine(TestCoroutine()); //StartCoroutine(메서드()) : 코루틴 메서드 시작
IEnumerator i = ACoroutine();
aCoroutine = StartCoroutine(i); //코루틴 인스턴스 생성 및 할당
//aCoroutine = StartCoroutine(ACoroutine());
//bCoroutine = StartCoroutine("BCoroutine", 1); //문자열로 메소드를 넣을 수도 있음
Coroutine b =
StartCoroutine("BCoroutine", 1);
StartCoroutine("BCoroutine", 2);
//코루틴은 별개의 루프가 관리해주는 방식, 실제론 절차적으로 동작함
//스크립트를 유니티상에서 끄더라도 코루틴은 안꺼짐, GameObject를 끄면 꺼짐
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
StopCoroutine(ACoroutine()); //정지안됨
//StopCoroutine(aCoroutine);
if (Input.GetKeyDown(KeyCode.B))
StopCoroutine("BCoroutine"); //정지됨
//StopCoroutine(bCoroutine);
if (Input.GetKeyDown(KeyCode.S))
StopAllCoroutines(); //해당 컴포넌트에서 돌린 코루틴만 다 정지시킴
}
//IEnumerable과 IEnumerator은 다른 것
private IEnumerator TestCoroutine() // 3 2 1이 각각 지연 실행됨
{
Debug.Log("3");
//yield return new WaitForSeconds(1f);
yield return wait1Sec;
Debug.Log("2");
yield return wait1Sec;
Debug.Log("1");
}
private IEnumerator ACoroutine() //A 로그를 띄운 후 다음으로 지연실행
{
while (true)
{
Debug.Log("A");
yield return null;
}
}
private IEnumerator BCoroutine(int _num) //B 로그를 띄운 후 다음으로 지연실행
{
while (true)
{
Debug.Log(_num + ": B");
yield return null;
}
}
}
start한 순서대로 코루틴이 순차적으로 돌아가는 것을 확인 할 수 있다.
using System.Collections;
using UnityEngine;
public class CoroutineExample : MonoBehaviour
{
private class WaitForMouseClick : CustomYieldInstruction //추상클래스
{
public override bool keepWaiting //keepWating 메소드를 오버라이드 해줘야 활용 가능함
{
get { return !Input.GetMouseButtonDown(1); } //마우스를 누르지 않으면 대기, 마우스를 누르면 웨이팅이 끝남
}
}
private void Start()
{
StartCoroutine(CounterCoroutine());
}
private IEnumerator CounterCoroutine()
{
Debug.Log("1");
yield return new WaitForSeconds(0.5f);
Debug.Log("2");
yield return AlphabetCoroutine(); //해당 코루틴이 끝날때 까지 대기함
Debug.Log("3");
yield return new WaitForSeconds(0.5f);
}
private IEnumerator AlphabetCoroutine()
{
Debug.Log("A");
yield return new WaitForMouseClick(); //마우스 클릭 될때까지 대기
Debug.Log("B");
yield return new WaitForSeconds(0.5f);
Debug.Log("C");
yield return new WaitForSeconds(0.5f);
}
}
이렇게 여러 조건들로 코루틴을 활용하는 것도 가능하다