본문 바로가기

정리 카테고리/개인복습&정리

코루틴을 여러개 쓰면 생기는일



코루틴을 2개 이상 쓸때 생각치 못한 현상이 일어나는것을 확인하기 위해 간단한 소스를 만들어 보았다.

아래 소스와 같이 작성하게 되면 코루틴 안의 코루틴이 1번 출력하는것이 아닌 2번 또는 3번을 한번에 출력하는것을 볼수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Test : MonoBehaviour {
    private int checkO = 0;
    private int checkT = 0;
    void Start () {
 
        StartCoroutine(this.checkOne());
        
    }
    //동작할 코루틴
    IEnumerator checkOne()
    {
        while (checkO<12)
        {
            checkO++;
           
            //메시지 출력
                Debug.Log("checkO는 현재:: <color=red>" + checkO+ "</color>");
            //한프레임 쉼
            if (checkO >= 5&&checkO<12)
            {
                Debug.Log("checkO는 현재:: <color=blue>" + checkO + "</color>");
                StartCoroutine(this.checkTwo());
            }
            yield return null;
        }
    }
    IEnumerator checkTwo()
    {
        while (checkT<5)
        {
            
            checkT++;
 
            //메시지 출력
            Debug.Log("checkT는 현재:: <color=lime>" + checkT + "</color>");
 
            yield return null;
        }
    }
}
 
cs








다음 소스중 안에서 도는 코루틴인 checkTwo가 한프레임 쉬던것을 쓴 yield return null에서 

바깥쪽에 있는 코루틴이 완료될때 까지를 기다리는 yield return StartCoroutine을 활용하면 1번씩 출력하게 된다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Tests : MonoBehaviour
{
    private int checkO = 0;
    private int checkT = 0;
    void Start()
    {
        //코루틴 CheckOne실행
        StartCoroutine(this.checkOne());
 
    }
    //동작할 코루틴
    IEnumerator checkOne()
    {
        while (checkO < 12)
        {
            //횟수체크
            checkO++;
 
            //메시지 출력
            Debug.Log("checkO는 현재:: <color=red>" + checkO + "</color>");
            if (checkO >= 5 && checkO < 12)
            {
                Debug.Log("checkO는 현재:: <color=blue>" + checkO + "</color>");
                //코루틴 checkTwo 실행
                StartCoroutine(this.checkTwo());
            }
            //한프레임 쉼
            yield return null;
        }
    }
    IEnumerator checkTwo()
    {
        while (checkT < 5)
        {
            //횟수 체크
            checkT++;
 
            //메시지 출력
            Debug.Log("checkT는 현재:: <color=lime>" + checkT + "</color>");
            //checkOne 코루틴이 끝날때 까지 대기
            yield return StartCoroutine(checkOne());
        }
    }
cs