13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityのWaitUntilは使わない

Posted at

#代わりはWhile
 代わりにWhileを使います。WaitUntilを使うと条件式が最初から真でも1フレーム消費してしまうようです。以下確認コードと結果。Unity2017.2 0p4 Windows版のEditorによるテストです。

WaitUntilTest.cs
using System.Collections;
using UnityEngine;

public class WaitUntilTest : MonoBehaviour
{
    [SerializeField]
    bool whileContinue = false;

    void Start()
    {
        Log("Start");
        StartCoroutine(TestWaitUntil());
        StartCoroutine(TestWaitForSeconds());
        StartCoroutine(TestWhile());
    }

    IEnumerator TestWaitUntil()
    {
        Log("TestWaitUntil");
        yield return new WaitUntil(() => true);
        Log("TestWaitUntilAfterBlock");
    }

    IEnumerator TestWaitForSeconds()
    {
        Log("TestWaitForSeconds");
        yield return new WaitForSeconds(0f);
        Log("TestWaitForSecondsAfterBlock");
    }

    IEnumerator TestWhile()
    {
        Log("TestWhile");
        while(whileContinue)
            yield return null;
        Log("TestWhileAfterBlock");
    }

    void Log(string message)
    {
        Debug.Log(Time.time.ToString("n5") + " :" + message);
    }
}
結果
0.00000 :Start
0.00000 :TestWaitUntil
0.00000 :TestWaitForSeconds
0.00000 :TestWhile
0.00000 :TestWhileAfterBlock
0.02000 :TestWaitUntilAfterBlock
0.02000 :TestWaitForSecondsAfterBlock

 個人的にはWaitUntilが好きです。「ここで他の処理を待っています」というのが明示できるからです。ただパフォーマンスに関わるとなれば仕方ありません。たかが1フレーム、されど1フレーム。見逃すと入力連打によるバグに繋がったりします。
 ついでにWaitForSecondsも調べました。同様に1フレーム消費してしまうようです。どうやらYieldInstructionには同じ性質がありそうです。

13
12
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
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?