0
3

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 3 years have passed since last update.

Unity 一定時間毎に動作させるコルーチン(Coroutine)の使い方 IEnumeratorとwhileの組み合わせ

Posted at

##0.0 はじめに
コルーチンはオブジェクトを一定時間毎に動作させるなど便利な使い方ができます。基本的な使い方を備忘録としてここに記します。

##1.0 コルーチンとは
コルーチンは1フレーム内では処理が終わらず、数フレームあるいはそれ以上かけて処理を実行する必要がある場合に用いられます。
イメージは処理を一時停止し、その間に別のプログラムを実行、終わったら処理を再開しているような感じで、処理方法に関係なく規則的に動作するオブジェクトやUIを作るときに役に立ちます。
データ型のIEnumerator(イテレーター)を返り値としてもつメソッドをつくり、そのメソッドをStartCoroutine()で呼び出します。

##2.0 毎フレーム実行
StartCoroutine()で一度Loop()を呼んであげると毎フレームループします。
yield returnのところで次のフレームまで待ちます。

test.cs
void Start () {
    // コルーチンを設定
    StartCoroutine(Loop());
}

// 毎フレームループします
private IEnumerator Loop() {
    while (true) {
        yield return null;
        Debug.Log("Loop");
    }
}

##3.0 指定した回数だけ実行
下記は10フレームだけループするプログラムです。
同じくyield returnのところで次のフレームまで待ちます。

test.cs
void Start () {
    // コルーチンを設定
    StartCoroutine(Loop(10));
}

// frameで指定したフレームだけループします
private IEnumerator Loop(int frame) {
    while (frame > 0) {
        yield return null;
        Debug.Log("Loop");
        frame--;
    }
}

##4.0 秒数を指定して実行
yield return のところをWaitForSecondsにします。引数(float)で秒の指定が出来ます。
指定した秒数だけ待ちます。

test.cs
void Start () {
    // コルーチンを設定
    StartCoroutine(Loop(10f));
}

// secondで指定した秒数ループします
private IEnumerator Loop(float second) {
    while (true) {
        yield return WaitForSeconds(second);
        Debug.Log("Loop");
    }
}
0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?