神様は有休消化中です。

Unity関連の技術ネタを書いてます。

【Unity】Graphicを継承したクラスでMissingReferenceExceptionが発生する

先日、Graphicを継承したクラスで何故かMissingReferenceExceptionが発生することがあったので共有。
結論から言うと、OnDisableをオーバーライドすると発生する様子。

テスト用にこんなクラスをすると、コンパイル時にMissingReferenceExceptionが発生します。

public class HogeUI : Graphic {
    protected override void OnDisable ()
    {
        /* なんらかの処理 */
    }
}

Exceptionの内容はこんな感じ。HogeUIが破棄されたのにアクセスしていますと。

MissingReferenceException: The object of type 'HogeUI' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.UI.Graphic.OnRebuildRequested () (at /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Graphic.cs:396)
UnityEngine.UI.GraphicRebuildTracker.OnRebuildRequested () (at /Users/builduser/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/GraphicRebuildTracker.cs:33)
UnityEngine.CanvasRenderer.RequestRefresh ()


おそらくGraphicクラスのOnDisableで何かしら必要な処理を行っていて、オーバーライドによって走らなくなったために起こっているのかと。

対応は以下のようにしました。

public class HogeUI : Graphic {
    protected override void OnDisable ()
    {
        base.OnDisable(); // 追加

        /* なんらかの処理 */
    }
}


Graphicクラスの関数をオーバーライドする場合は、基本的に親クラスの処理を呼び出したほうがいいのかもしれません。