본문 바로가기

게임 개발 공부 정리

[Unity] 코루틴 정리 코드 - 20 09 17

코루틴은 루프 함수안에서 순차적으로 실행되는 코드들과 별개로 병렬로 코드들이 실행 될 수 있게 하는 것이다.

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

public class Test : MonoBehaviour
{

    Coroutine MyCoroutine1;

    private IEnumerator myCoroutine2;

    void Start()
    {
        StartCoroutine(StopCo());
        //기본 실행 방법

        MyCoroutine1 = StartCoroutine(Coroutine1(1, 2, 3, 4));
        //시작한 코루틴을 종료 등 여러 조작을 하기 위해서 변수에 넣는다 

        StartCoroutine("Coroutine2", 1);
        //시작할 수 있는 또 다른 방법이다.
        //윗 방법과 다르게 인수를 하나 밖에 못넘긴다.

        myCoroutine2 = Coroutine3();
        StartCoroutine(myCoroutine2);
        /*Mycoroutine1 변수를 사용하는 방법과 동일해 보이지만 인수를 많이 넘길때 이게 더 편리하다.
         * 코루틴을 호출 할때마다 일일이 인수를 입력해야 하는것 보다 변수에 담은 다음, 스타트 코루틴을 해주는것이다 */


    }

    IEnumerator Coroutine1(int a, int b, int c, int d)
	{
        for(int i = 0; i <= d; i++)
		{
            yield return new WaitForSeconds(1.0f);
            Debug.Log(+i);
        }
	}

    IEnumerator Coroutine2(int only_one)
	{
        for(int i = 0; i <= only_one; i++)
        {
            Debug.Log(+i);
            yield return new WaitForSeconds(1.0f);
        }
	}

    IEnumerator Coroutine3()
	{
        for(int i = 0; i < 10; i++)
		{
            yield return null; //1프레임씩 대기
            Debug.Log(+i);
		}
	}

    IEnumerator StopCo()
	{
        yield return new WaitForSeconds(1.0f);
        StopCoroutine("MyCoroutine1");
        //코루틴 중단 첫번째 방법이다.
        //변수에 넣어진 코루틴만 멈출수있다.

        yield return new WaitForSeconds(1.0f);
        StopCoroutine("Coroutine2");
        //두번째 방법

        yield return new WaitForSeconds(1.0f);
        StopAllCoroutines();
        //모든 코루틴을 중단한다.
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}