본문 바로가기

game dev/unity

Coroutine 코루틴의 2가지 기능 ex)Fade In

코루틴의 대표적인 2가지 기능을 알아보자

1. 대기시간 생성

2. 비동기 방식으로 멀티쓰레드 실행(다수의 코루틴을 병렬적 실행)

1. 대기시간 생성

아래는 활용도 예시이다.

 

 

Fade In

 

 

- Fade In

1. ui > image 생성하고 앵클을 alt를 누른채 오른쪽 최하단을 눌러 전체 화면을 펴준다.

2. Fade 컴포넌트를 추가해준다.

 

3. Fade 클래스 코드 작성

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Fade : MonoBehaviour
{

    public Image FadeImage;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine("FadeIn");   // 코루틴 시작
    }

    // 서서히 투명해지는 Fade In 구현
    IEnumerator FadeIn()
    {
        Color startColor = FadeImage.color;

        // 투명도인 알파값을 1% 씩 빼준다.
        for (int i = 0; i < 100; i++)
        {
            startColor.a = startColor.a - 0.01f;
            FadeImage.color = startColor;
            yield return new WaitForSeconds(0.01f); // 0.01초 대기 후 실행
        }
    }
}

 

 

2.  비동기 방식(async)으로 멀티쓰레드 실행(다수의 코루틴을 병렬적 실행)

각각 3초와 5초의 대기시간을 두고 코루틴을 실행해보자

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloCoroutine : MonoBehaviour
{
    void Start()
    {
        StartCoroutine("First");
        StartCoroutine("Second");
        Debug.Log("END");
    }

    IEnumerator First()
    {
        Debug.Log("First start");
        yield return new WaitForSeconds(3f);
        Debug.Log("First end");
    }

    IEnumerator Second()
    {
        Debug.Log("Second start");
        yield return new WaitForSeconds(5f);
        Debug.Log("Second end");
    }
}

 

기존 코드의 방식은 동기방식(sync). 순차적 실행

 

- 예상 결과값 -

First start

(3초대기)

First end

Second start

(5초대기)

Second end

END

 

그러나 코루틴은 여러개의 코루틴을 병렬적으로 동시에 실행한다. 

 

- 실제 결과값 -

First start

Second start

END

(3초대기)

First end

(2초 대기)

Second end

END