MRが楽しい

MRやVRについて学習したことを書き残す

UnityでMonoBehaviourを継承したクラスを継承した場合の動作を試す

本日は Unity の小ネタ枠です。
Unity で MonoBehaviour を継承したクラスを継承した場合の動作について気になり試したので記事に残します。

UpdateなどのUnity関数を上書きする

最初に Update や OnEnable をそのまま上書きしたケースを試しました。
以下の基底クラスと継承クラスを用意しました。
・BaseClass.cs

using UnityEngine;

public class BaseClass : MonoBehaviour
{
    void OnEnable()
    {
        ShowDebugLog("BaseClass : OnEnable");
    }

    void Update()
    {
        ShowDebugLog("BaseClass : Update");
    }
    
    void OnDisable()
    {
        ShowDebugLog("BaseClass : OnDisable");
    }

    protected void ShowDebugLog(string message)
    {
        Debug.Log(message);
    }
}

・InherClass.cs

public class InherClass : BaseClass
{
    void OnEnable()
    {
        ShowDebugLog("InherClass : OnEnable");
    }
    
    void Update()
    {
        ShowDebugLog("InherClass : Update");
    }
    
    void OnDisable()
    {
        ShowDebugLog("InherClass : OnDisable");
    }
}

これで継承クラスをシーンにアタッチして動作を確認します。
以下の通り、継承クラスでも問題なく Update, OnEnable, OnDisable などの Unity のライフサイクルは動作します。

Unity関数以外を上書きしてライフサイクルから呼び出す

次に以下のケースを試してみました。
継承クラスで Unity 関数以外を上書きして基底クラスのライフサイクルから対象の関数を呼び出します。
・BaseClass2.cs

using UnityEngine;

public class BaseClass2 : MonoBehaviour
{
    void OnEnable()
    {
        OnEnableTask();
    }

    void Update()
    {
        UpdateTask();
    }
    
    void OnDisable()
    {
        OnDisableTask();
    }

    protected virtual void OnEnableTask()
    {
        ShowDebugLog("BaseClass : OnEnable");
    }

    protected virtual void UpdateTask()
    {
        ShowDebugLog("BaseClass : Update");
    }

    protected virtual void OnDisableTask()
    {
        ShowDebugLog("BaseClass : OnDisable");
    }

    protected void ShowDebugLog(string message)
    {
        Debug.Log(message);
    }
}

・InherClass2.cs

public class InherClass2 : BaseClass2
{
    protected override void OnEnableTask()
    {
        ShowDebugLog("InherClass : OnEnable");
    }
    
    protected override void UpdateTask()
    {
        ShowDebugLog("InherClass : Update");
    }
    
    protected override void OnDisableTask()
    {
        ShowDebugLog("InherClass : OnDisable");
    }
}

同じくこちらも継承クラスをシーンにアタッチして動作を確認します。
以下の通り、継承クラスで Update, OnEnable, OnDisable などの Unity のライフサイクルのタイミングでオーバーライドした関数が呼び出されて動作します。

UnityEngine に依存していないコードのロジック部分のみを別ファイルに切り出したい場合に利用できそうです。