うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】WaitForSeconds のキャッシュ

前の記事で YieldInstruction を利用するときに

yield return new WaitForSeconds(0.01f);

とすると呼び出し毎にゴミが出るとのことがあったので
それの対応としてWaitForSeconds をグローバルで管理して使えるクラスを作成

これを利用すると WaitForSeconds を利用した処理をする場合でも2行にならずに記述できます

using System.Collections.Generic;
using UnityEngine;
 
public static class WaitForSecondsCache
{
    private static Dictionary<float, WaitForSeconds> _dic = new Dictionary<float, WaitForSeconds>();
    
    private static WaitForSeconds Get(float seconds)
    {
        if (!_dic.ContainsKey(seconds))
        {
            _dic.Add(seconds, new WaitForSeconds(seconds));
        }
 
        return _dic[seconds];
    }
 
    public static IEnumerator Wait(float seconds)
    {
        var wait = Get(seconds);
        yield return wait;
    }
}

使いかた

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class SampleMonoBehaviour : MonoBehaviour
{
    private IEnumerator Start()
    {
        while (true)
        {
            yield return WaitForSecondsCache.Wait(2f);
        }
    }
}