コガネブログ

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

【Unity】Action デリゲートは 104B の GC Alloc が発生するが、インターフェイスであれば発生しない

概要

Action デリゲートはとても便利ですが、104B の GC Alloc が発生します
もしも Action デリゲートを Update 関数などで頻繁に呼び出す場合は
インターフェイスに置き換えることで GC Alloc の発生を防ぐことができます

Action デリゲート

using System;
using System.Collections;
using UnityEngine;

public class Example : MonoBehaviour
{
    private IEnumerator Start()
    {
        while ( true )
        {
            ActionHandler( () => TestAction() );
            yield return null;
        }
    }

    private void ActionHandler( Action act )
    {
        act();
    }

    private void TestAction()
    {
    }
}

f:id:baba_s:20171228192348p:plain

インターフェイス

using System.Collections;
using UnityEngine;

public interface IInterface
{
    void Test();
}

public class Example : MonoBehaviour, IInterface
{
    private IEnumerator Start()
    {
        while ( true )
        {
            InterfaceHandler( this );
            yield return null;
        }
    }

    private void InterfaceHandler( IInterface i )
    {
        i.Test();
    }

    public void Test()
    {
    }
}

f:id:baba_s:20171228192557p:plain

関連記事