关于继承MonoBehaviour的一些记录

时间:2023-03-08 20:53:29

在开发游戏中,为了减少不必要的代码量,我们经常会继承MonoBehaviour,那么MonoBehaviour内部的内置方法Start、Update等等如果在父类中定义了,在子类中再次定义会发生什么事呢?

我们来看看几个示例:

 using UnityEngine;
using System.Collections; public class Test1 : MonoBehaviour
{
void Start()
{
Debug.Log("Test1 Start");
} void Update()
{
Debug.Log("Test1 Update");
}
}
 using UnityEngine;
using System.Collections; public class Test2 : Test1
{
void Start()
{
Debug.Log("Test2 Start");
} void Update()
{
Debug.Log("Test2 Update");
}
}

我们将Test2.cs绑定到一个GameObject上,运行看看结果:

关于继承MonoBehaviour的一些记录

我们会发现Test2的方法覆盖了Test1的方法,同时Start、Update等内置的方法不是虚函数,所以无法使用base.Start()来调用父类的方法。

下面我们修改Test2如下:

 using UnityEngine;
using System.Collections; public class Test2 : Test1
{
}

运行看看:

关于继承MonoBehaviour的一些记录

我们会发现如果在子类不定义Start、Update等方法会调用父类的对应方法,注意:定义了但函数体为空则不会调用父类的同名方法,类似于取消该方法的效果。

如果我们需要Start、Update是虚函数该怎么办呢?很简单,自己写一个:

 using UnityEngine;
using System.Collections; public class Test1 : MonoBehaviour
{
void Start()
{
OnStart();
} protected virtual void OnStart()
{ } void Update()
{
OnUpdate();
} protected virtual void OnUpdate()
{ }
}

这样我们在其子类直接override方法OnStart、OnUpdate就行了,当前前提是其子类不能再定义Start和Update方法。