【Unity】GC 発生タイミングを任意制御する

DEVELOP, Unity

GC 処理を一定期間ごとに小刻みに行うコード。

using UnityEngine;
 
public class GarbageCollectionManager : MonoBehaviour
{
    [SerializeField]
    private float maxTimeBetweenGarbageCollections = 60.0f;
 
    private float timeSinceLastGarbageCollection = 0.0f;
 
    /// <summary>
    /// 開始.
    /// </summary>
    private void Start()
    {
#if !UNITY_EDITOR
        GarbageCollector.GCMode = GarbageCollector.Mode.Disabled;
#endif// You might want to run this during loading times, screen fades and such.// Events.OnScreenFade += CollectGarbage;
    }
 
    /// <summary>
    /// 更新.
    /// </summary>
    private void Update()
    {
        timeSinceLastGarbageCollection += Time.unscaledDeltaTime;
        if (timeSinceLastGarbageCollection > maxTimeBetweenGarbageCollections)
        {
            CollectGarbage();
        }
    }
 
    private void CollectGarbage()
    {
        timeSinceLastGarbageCollection = 0f;
        Debug.Log("Collecting garbage");
 
#if !UNITY_EDITOR// Not supported on the editorc
    GarbageCollector.GCMode = GarbageCollector.Mode.Enabled;
    GC.Collect();
    GarbageCollector.GCMode = GarbageCollector.Mode.Disabled;
#endif
    }
}

目次

GC発生テストコード

using UnityEngine;
public class GenerousGarbageCreator : MonoBehaviour
{
    [SerializeField] private int garbageCreationRate = 1024;
    private static int[] garbage;
    void Update()
    {
        garbage = new int[garbageCreationRate];
    }
}

留意点

GarbageCollector.Mode に GarbageCollector.Mode.Disabled; を指定したまま GC.Collect() を呼ばないでいるとゴミが溜まりまくってEditor や端末がクラッシュするので必ず GC.Collect() を呼ぶこと。

Posted by kazupon