Coroutine

조성원·2025년 5월 17일

-Coroutine 가이드-
https://docs.unity3d.com/kr/2021.3/Manual/Coroutines.html

-Thread란-
https://jerryjerryjerry.tistory.com/184

-Thread와 Coroutine의 차이점-
https://velog.io/@haero_kim/Thread-vs-Coroutine-%EB%B9%84%EA%B5%90%ED%95%B4%EB%B3%B4%EA%B8%B0#coroutine







코루틴은 작업을 다수의 프레임에 분산하는 메서드

위 메서드는 한 프레임에 모든 함수를 실행시키지만
코루틴을 사용하면 프레임 단위로 분산 실행할 수 있다.



코루틴은 스레드가 아니다

Thread는 각자 메모리 공간을 할당 받아 병렬성, 동시성 작업을 수행할 수 있다.
코루틴은 하나의 스레드에서 프레임 단위로 잠깐 멈췄다가 나중에 이어서 하는 분할 형식이고
스레드는 여러 스레드를 병렬로, 또는 시분할로 실행되는 형식이다.


코루틴

프레임 단위로 흐름을 멈췄다가 이어갈 수 있는 함수.
시간 지연, 다음 프레임까지 대기, 조건부 대기, 정지, 반복 호출 등이 가능하다.

using UnityEngine;

public class DelayedAttack : MonoBehaviour
{
    public float delay = 1f;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("공격 준비 중...");
            StartCoroutine(AttackAfterDelay());
        }
    }

    IEnumerator AttackAfterDelay()
    {
        yield return new WaitForSeconds(delay); // 1초 대기
        Debug.Log("공격 실행!");
        // 여기에 실제 공격 로직 넣기
    }
}

InvokeRepeating과의 차이

InvokeRepeating과 코루틴은 시간 지연을 담당한다는 공통점이 있지만 코루틴은 흐름 제어까지 가능해서 자유도가 높다.

//1초 뒤에 Fire를 호출하고 2초마다 반복 호출
InvokeRepeating("Fire", 1f, 2f);



IEnumerator FireRepeatedly()
{
    yield return new WaitForSeconds(1f); // 시작 지연

    while (true)
    {
        Fire();
        yield return new WaitForSeconds(2f); // 반복 주기
    }
}
StartCoroutine(FireRepeatedly());
profile
direction *= -1;

0개의 댓글