Unity:Coroutine挙動メモ

同じ Coroutine を複数回まわすと Coroutine の処理がかぶる。

myCoroutine1 の while の一回目(up++

myCoroutine2 の while の一回目(up++

myCoroutine1 の while の二回目(up++

myCoroutine2 の while の二回目(up++

.......etc

    

public class test : MonoBehaviour
{
    int up;
    // Start is called before the first frame update
    void Start()
    {
        up = 0;
        StartCoroutine(MYCoroutine(2));
    }

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

    }

    public IEnumerator MYCoroutine(int num)
    {
        for (int i = 0; i < num; i++)
        {
            StartCoroutine(myCoroutine(i));
            yield return null;
        }
    }

    public IEnumerator myCoroutine(int i)
    {
        while (up < 10)
        {
            up++;
            Debug.Log("i =" + i + "/ up =" + up);
            yield return new WaitForSeconds(0.07f);
        }
    }

}


ログはこんな感じ

連続させないようにするのも考えてみた。正しいかはわからない。
これだと
ANOTHERCoroutine1 の while 1

ANOTHERCoroutine1 の while 2

ANOTHERCoroutine1 の while 3

...etc
ANOTHERCoroutine2 の while 1

ANOTHERCoroutine2 の while 2

ANOTHERCoroutine2 の while 2

...etc
になる。

public class test : MonoBehaviour
{
    int up;
    int down;
    bool IsWaitingCoroutine;
    // Start is called before the first frame update
    void Start()
    {
        up = 0;
        StartCoroutine(anotherCoroutine(5));
    }

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

    }
    public IEnumerator anotherCoroutine(int num)
    {
        for (int i = 0; i < num; i++) 
        { 
            StartCoroutine(ANOTHERCoroutine(i,10)); 
            yield return null; 
        } 
    } 
    public IEnumerator ANOTHERCoroutine(int i,int num) { 
        while(down > 0)
        {
            yield return null;
        }
        int temp = num;
        IsWaitingCoroutine = true;
        while (temp > 0)
        {
            up++;
            temp--;
            down = temp;
            Debug.Log("i =" + i + "/ up =" + up);
            yield return new WaitForSeconds(0.07f);
        }
        IsWaitingCoroutine = false;
    }
}

ログはこんな感じ

ちゃんと1度目の ANOTHERCoroutine が終わってから 二度目のが動いている。

これboolでもいい

public class test : MonoBehaviour
{
bool isWaitingCoroutine;
int down;
// Start is called before the first frame update
void Start()
{
up = 0;
StartCoroutine(anotherCoroutine(5));
}

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

}
public IEnumerator anotherCoroutine(int num)
{
for (int i = 0; i < num; i++)
{
StartCoroutine(ANOTHERCoroutine(i,10));
yield return null;
}
}
public IEnumerator ANOTHERCoroutine(int i,int num) {
while(IsWaitingCoroutine)
{
yield return null;
}
int temp = num;
while (temp > 0)
{
up++;
temp--;
Debug.Log("i =" + i + "/ up =" + up);
yield return new WaitForSeconds(0.07f);
}
}
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA