コガネブログ

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

【Unity】MaskableGraphic を継承した uGUI コンポーネントは初期化や破棄のタイミングで GC Alloc が走る?

はじめに

https://bitbucket.org/Unity-Technologies/ui/src/2017.3/UnityEngine.UI/UI/Core/MaskableGraphic.cs

protected override void OnEnable()
{
    ...

    if (GetComponent<Mask>() != null)
    {
        MaskUtilities.NotifyStencilStateChanged(this);
    }
}

protected override void OnDisable()
{
    ...

    if (GetComponent<Mask>() != null)
    {
        MaskUtilities.NotifyStencilStateChanged(this);
    }
}

MaskableGraphic を継承した uGUIコンポーネントは
OnEnable や OnDisable で Mask コンポーネントを GetComponent するため、
初期化や破棄のタイミングで GC Alloc が走ってしまうようです

f:id:baba_s:20180917133854p:plain

試しにシーンに Canvas と Image を配置して
Canvas のアクティブを切り替えてみたところ
1.6 KB の GC Alloc が発生することが確認できました

MaskableGraphic.cs の GetComponent の処理を削除して DLL を作成したところ、
GC Alloc が発生しなくなることがわかりました

f:id:baba_s:20180917134042p:plain

Unity 2018.2.1f1 では GC Alloc が発生しなかったので、
Unity 2018 以降では修正されているかもしれません

参考サイト様