この記事について
この記事ではCoroutine(コルーチン)での非同期処理をスクリプトで制御する方法が学べます。
この記事でわかること
- Coroutine(コルーチン)の基本的な使い方
- フェード処理・スポーンなど、時間経過を使った処理の方法
- yield returnの使い方と種類
- Coroutineの途中停止方法(yield break)
- メモリ効率を高める最適化の方法
Coroutine(コルーチン)とは?
Coroutine(コルーチン)については以下の記事を参考にしてください。
Coroutine(コルーチン)の使い方
Coroutine(コルーチン)の準備
まずはヒエラルキーで右クリックをして空のGameObjectを1つ用意します。
・「右クリック」→「Create Empty」
次にスクリプトを作成してCreate Emptyにアタッチしてください。

WaitForSecondsを使用した非同期処理
Coroutineの基本的な使い方として「yield return new WaitForSeconds()」で一定時間待って処理することができます。
using System.Collections;
using UnityEngine;
public class Coroutine_Yeild : MonoBehaviour
{
void Start()
{
Debug.Log("Time : " + Time.time);
StartCoroutine(ExampleCoroutine_wait());
StartCoroutine(ExampleCoroutine_null1());
StartCoroutine(ExampleCoroutine_null2());
}
IEnumerator ExampleCoroutine_wait()
{
yield return new WaitForSeconds(3); // 3秒待つ
Debug.Log("ExampleCoroutine_wait : " + Time.time);
}
IEnumerator ExampleCoroutine_null1()
{
Debug.Log("ExampleCoroutine_null1 : Start");
yield return null; // ここで一旦中断し、次のフレームで再開
Debug.Log("ExampleCoroutine_null1 : " + Time.time);
}
IEnumerator ExampleCoroutine_null2()
{
Debug.Log("ExampleCoroutine_null2 : Start");
yield return null; // ここで一旦中断し、次のフレームで再開
Debug.Log("ExampleCoroutine_null2 : " + Time.time);
}
}
実行してみるとWaitForSeconds(3)で約3秒で呼ばれてますね。
また、2つのyeild return nullでは1フレーム待機ができますね。もし、フレーム待機していないとnull1とnull2のStartが連続で呼ばれないのでわかりやすいですね。
yield breakで途中停止
非同期処理を途中で停止させたいときは「yield break」を使うと強制的にコルーチンを終了できます。
using System.Collections;
using UnityEngine;
public class Coroutine_Yeild : MonoBehaviour
{
void Start()
{
Debug.Log("Time : " + Time.time);
StartCoroutine(FadeOut());
}
//条件を満たしたら即終了
IEnumerator FadeOut()
{
Debug.Log("ProcessTime : " + Time.time);
yield return new WaitForSeconds(3);
yield break; // コルーチンを即終了
Debug.Log("FinishTime : " + Time.time);
}
}
実行してみると「Debug.Log(“FinishTime : ” + Time.time);」が実行されていませんね。これはその直前で終了したということになります。
Coroutine(コルーチン)のパフォーマンス最適化
最適化①:WaitForSecondsRealtimeでGC対策
WaitForSeconds()は毎回新しいオブジェクトを生成するため、メモリ負荷を軽減するために「WaitForSecondsRealtime()」使うと良い。
private WaitForSecondsRealtime waitTime = new WaitForSecondsRealtime(1.0f);
IEnumerator ExampleCoroutine()
{
yield return waitTime; // GCの負担を減らす
Debug.Log("1秒後の処理");
}
最適化②:IEnumeratorのキャッシュ
IEnumeratorをキャッシュすると、余計なメモリ確保を防ぐ!
private IEnumerator fadeOutCoroutine;
void Start()
{
fadeOutCoroutine = FadeOut();
}
void StartFade()
{
StartCoroutine(fadeOutCoroutine);
}
まとめ
- Coroutineは時間制御・非同期処理に最適な仕組み
- yield returnで処理を一時停止/再開できる
- yield breakで途中停止も可能
- 最適化のポイント(WaitForSecondsのキャッシュ)も意識しよう!