유니티

코루틴

잼잼재미 2023. 11. 30. 08:58

코루틴?


시간의 경과에 따른 명령을 주고싶을 때 사용하는 문법

 

 

Update를 사용하면 안되는가?


update 함수는 매프레임 호출되기 때문에 비용이 많이 들고 일시적인 동작을 구현하기에는 맞지 않음

 

 

코루틴 반환타입


명시된 순간만큼 동작을 중지하고 제어권을 유니티에 돌려주고 다음 프레임에 정지했던 지점부터 코드 실행

  • yield return null; : 한 프레임 동안만 기다림
  • yield return new WaitForSeconds(2f); : 생성자의 매개변수 시간만큼 기다림 (게임 시간)
  • yield return new WaitForSecondsRealtime(2f); : 생성자의 매개변수 시간만큼 기다림 (실제 시간), TimeScale에 영향을 받지 않음
  • yield return new WaitForFixedUpdate(); : FixedUpdate 과정이 끝나고 제어권을 돌려 받음
  • yield return new WaitForEndOfFrame(); : Update, 화면을 렌더링하는 과정 등 한 프레임이 지나가는 과정 전체가 끝난 뒤, 마지막에 제어권을 돌려 받음

 

 

예시


Update 사용

public bool isDelay;
public float delayTime = 2f;
float timer = 0f;

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        if(!isDelay)
        {
            isDelay = true;
            Debug.Log("Attack");
        }
        else
        {
            Debug.Log("Delay");
        }
    }

    if(isDelay)
    {
        timer += Time.deltaTime;

        if(timer >= delayTime)
        {
            timer = 0f;
            isDelay = false;
        }
    }
}

 

 

코루틴 사용

public bool isDelay;
public float delayTime = 2f;
float timer = 0f;


void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        if(!isDelay)
        {
            isDelay = true;
            Debug.Log("Attack");
            StartCoroutine(CountAttackDelay()); // 코루틴 실행 함수
        }
        else
        {
            Debug.Log("Delay");
        }
    }
}

IEnumerator CountAttackDelay()
{
    yield return new WaitForSeconds(delayTime);

    // 코루틴이 제어권을 돌려 받은 후, 실행할 코드 작성
    isDelay = false;
}

 

 

주의사항


  1. strat 함수 호출된 이후, 게임오브젝트가 활성화된 상태에서 호출해야 한다.
  2. 코루틴 내부의 반복문에 yield return 사용해야 한다.

'유니티' 카테고리의 다른 글

사운드  (0) 2023.12.04
프리팹 생성  (0) 2023.11.30
Vector  (0) 2023.11.29
Image Sprite 변경  (1) 2023.11.29
캐릭터 선택  (1) 2023.11.29