LoginSignup
15
22

More than 5 years have passed since last update.

コルーチンのサンプル集

Posted at

非同期処理
関数を任意のタイミングで中断・再開できる機能

xxx秒後にUpdate関数を実行する

private IEnumerator Start () {
    // enabled = true にして初めてUpdate()関数が走る
    enabled = false;
    yield return new WaitForSeconds(5);
    enabled = true;
}

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

for文の内部をxxx秒ごとに実行する

void Start () {
    StartCoroutine("Sample", 60);
}

IEnumerator Sample(int len) {
    // for文の内部を0.1秒ごとに実行する
    for (int i = 0; i < len; i++){
        yield return new WaitForSeconds(0.1f);
        Debug.Log("i: " + i);
    }
}

1フレームごとに実行する

void Start () {
    StartCoroutine("Sample", 60);
}

IEnumerator Sample(int len) {
    // 1フレームごとに実行する
    for (int i = 0; i < len; i++) {
        yield return null;
        Debug.Log("i: " + i);
    }
}

コルーチン内で別のコルーチンを実行

番号は、Logの出力される順番

void Start () {
    StartCoroutine("Sample1");
}

IEnumerator Sample1() {
    Debug.Log("Sample1 start"); // ①
    yield return StartCoroutine("Sample2");
    Debug.Log("Sample1 end");   // ④
}
IEnumerator Sample2() {
    Debug.Log("Sample2 start"); // ②
    yield return new WaitForSeconds(1f);
    Debug.Log("Sample2 end");   // ③
}

コルーチンを止める

3秒以内にスペースボタンを押せば、コルーチンの処理が止まる。

void Update () {
    if(Input.GetKeyDown(KeyCode.Space)){
        StopCoroutine("StartTimer");
    }
}

IEnumerator StartTimer() {
    yield return new WaitForSeconds(3f);
    Explode();
}
void Explode() {
    Debug.Log("どっかーん");
}

一時停止・再開

メソッドのIEnumeratorを事前に取得しておくと、一時停止・再開できる。

MouseDownしたら1フレームごとにカウントしていく
MouseUpしたら一時停止
再度MouseDownしたら、MouseUpした地点から再開

IEnumerator coroutineMethod;

void Start () {
    coroutineMethod = Sample(1000);
}

void OnMouseDown() {
    StartCoroutine(coroutineMethod);
}
void OnMouseUp() {
    StopCoroutine(coroutineMethod);
}

IEnumerator Sample(int len) {
    for (int i = 0; i < len; i++) {
        yield return null;
        Debug.Log("i: " + i);
    }
}

ゲーム終了時

コルーチンを全て止める

StopAllCoroutines();

参考
UnityのCoroutine(コルーチン)でできる事のメモ
Unityのコルーチン機能を使う
Unityのコルーチンの使い方をまとめてみた

15
22
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
15
22