LoginSignup
0
0

More than 3 years have passed since last update.

unity Coroutine

Last updated at Posted at 2020-01-13
using UnityEngine;
using System.Collections;

public class Sample : MonoBehaviour
{
    private bool update;

    private void Start()
    {
        update = false;
        StartCoroutine("ShowMessage");
    }

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

    private IEnumerator ShowMessage()
    {
         Debug.Log("GameStart!");
         yield return new WaitForSeconds(3);

         update = true;
         yield return null;
    }
}

解説。
StartCoroutine("メソッド名")
これで実行したいメソッドをコルーチン として実行できる。

メソッドの戻り値はIEnumeratorにする。
yield return new WaitForSeconds(秒数);
これでその部分で秒数分止めることができる。

yield return null;
これでこのメソッドが終わりであることを宣言している。

実行の流れとしては、
1.Startが実行される。
まずupdateフラグをオフにする。
次にメッセージをコンソールに表示するメソッドを実行する
2.1のStartCoroutineによりShowMessageに入る。
まずGameStart!のメッセージがコンソールに表示される。
yield return new WaitForSeconds(3)
ここで一旦メソッド から抜けてその後の部分が実行される

3.2から3秒経過したらyield return new WaitForSeconds(3)より後の部分が勝手に実行される。

0
0
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
0
0