LoginSignup
5
4

More than 5 years have passed since last update.

IEnumeratorを待つのにStartCroutine()とMoveNext() + Currentの違いを検証

Posted at

調べたこと

UnityでIEnumerator()を待つ場合、StartCoroutineを使う方法とMoveNext()メソッドとCurrentプロパティを使う方法がある。
2種類の書き方にはどんな違いあるか気になったので調べてみた。

検証コード

using UnityEngine;
using System.Collections;

public class IEnumeratorBehavior : MonoBehaviour
{
    const int count = 3;

    void Start ()
    {
        Debug.Log("start");
        StartCoroutine(test1());
        StartCoroutine(test2());
    }

    void Update ()
    {
        Debug.Log("update");
    }

    IEnumerator test1()
    {
        yield return StartCoroutine(ie("test1"));
    }

    IEnumerator test2()
    {
        var e = ie("test2");
        while (e.MoveNext())
        {
            yield return e.Current;
        }
    }

    IEnumerator ie(string s)
    {
        for(int i=0; i<count; ++i)
        {
            Debug.LogWarning(s + " " + i);
            yield return null;
        }
    }
}

実行結果

result.jpg
Unity 5.2.1p4で確認

結論

どっちも挙動は変わらなかったから短く書ける StartCoroutine() の方が良さげ

実行結果を見て「おや、出力順はなんでこうなる…」と思われた方は以下の「イベント関数の実行順」もご参考ください。
http://docs.unity3d.com/ja/current/Manual/ExecutionOrder.html

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4