スポンサーリンク

【Unity】コルーチンを止める方法

Unity

コルーチンの内側から止める

参考プログラム

using System.Collections;
using UnityEngine;

//コルーチンテストクラス
public class CroutineTest : MonoBehaviour
{
    private void Start()
    {
        //コルーチンをスタートさせる
        StartCoroutine(TestCroutine());
    }

    private IEnumerator TestCroutine()
    {
        int endCount = 10;      //コルーチン終了カウント
        int count = 0;          //カウント

        float waitTime = 5.0f;  //待機時間

        //無限ループ
        while (true)
        {
            //カウントが終了カウントを超えたら
            if (count > endCount)
            {
                Debug.Log("終了");
                yield break;
            }

            //待機時間待つ
            yield return new WaitForSeconds(waitTime);
            count++;
        }
    }
}

yield breakを使う

yield break;

コルーチンを中から止めたい時は、止めたいタイミングでyield break;を定義しておくことで、停止(終了)することが出来ます。

コルーチンの外側から止める

参考プログラム

using System.Collections;
using UnityEngine;

//コルーチンテストクラス
public class CroutineTest : MonoBehaviour
{
    private Coroutine _coroutine;    //コルーチンのインスタンス保存用

    void Start()
    {
        //コルーチンをスタートさせる
        _coroutine = StartCoroutine(TestCroutine());
    }

    //止めたいタイミングで呼び出す
    public void TestStop()
    {
        //コルーチンを止める
        StopCoroutine(_coroutine);
    }

    private IEnumerator TestCroutine()
    {
        int endCount = 10;      //コルーチン終了カウント
        int count = 0;          //カウント

        float waitTime = 5.0f;  //待機時間

        //無限ループ
        while (true)
        {
            //待機時間待つ
            yield return new WaitForSeconds(waitTime);
            count++;
        }
    }
}

StopCoroutineを使う

StopCoroutine(_coroutine);

コルーチンを外側から止めたい場合は、StartCroutineをする際に、コルーチンのインスタンスを保持しておいて、StopCoroutineの引数に渡すことで、停止することが出来ます。

タイトルとURLをコピーしました