コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】コルーチン関連の便利な機能を使用できる「CoroutineHelper」紹介

はじめに

「CoroutineHelper」を Unity プロジェクトに導入することで
コルーチン関連の便利な機能を使用できるようになります

使用例

using Hont;
using System.Collections;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Awake()
    {
        // コルーチンを開始
        CoroutineHelper.StartCoroutine( Hoge() );

        // 指定された秒後に実行
        CoroutineHelper.DelayInvoke( () => print( "ピカ" ), 2f );

        // 次のフレームに実行
        CoroutineHelper.DelayNextFrameInvoke( () => print( "ライ" ) );

        // コルーチンをグループ化して開始
        var group = CoroutineHelper.Factory.CreateCoroutineGroup();
        group.StartCoroutine( Hoge() );
        group.StartCoroutine( Hoge() );
        group.StartCoroutine( Hoge() );
        group.StartCoroutine( Hoge() );
        group.StopAllCoroutines();

        // コルーチンをプール化して GC Alloc を防ぐ
        var pool = CoroutineHelper.Factory.CreateCoroutinePool( 10 );
        pool.TryStartCoroutineInPool( Hoge() );

        if ( pool.HasCoroutineIdle )
        {
            pool.StartCoroutine( Hoge() );
        }

        // コルーチンの数を取得
        Debug.Log( CoroutineHelper.CoroutineCount );

        // コルーチンのプールのサイズを取得
        Debug.Log( CoroutineHelper.PoolTotalSize );
    }

    private IEnumerator Hoge()
    {
        // WaitForSeconds などをプール化して GC Alloc を防ぐ
        var seconds = CoroutineHelper.Pool_WaitForSeconds.Spawn();
        yield return seconds.Reset( 1f );
        CoroutineHelper.Pool_WaitForSeconds.Despawn( seconds );
    }
}