zoukankan      html  css  js  c++  java
  • 关于继承MonoBehaviour的一些记录

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

    我们来看看几个示例:

     1 using UnityEngine;
     2 using System.Collections;
     3 
     4 public class Test1 : MonoBehaviour
     5 {
     6     void Start()
     7     {
     8         Debug.Log("Test1 Start");
     9     }
    10     
    11     void Update()
    12     {
    13         Debug.Log("Test1 Update");
    14     }
    15 }
     1 using UnityEngine;
     2 using System.Collections;
     3 
     4 public class Test2 : Test1
     5 {
     6     void Start()
     7     {
     8         Debug.Log("Test2 Start");
     9     }
    10 
    11     void Update()
    12     {
    13         Debug.Log("Test2 Update");
    14     }
    15 }

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

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

    下面我们修改Test2如下:

    1 using UnityEngine;
    2 using System.Collections;
    3 
    4 public class Test2 : Test1
    5 {
    6 }

    运行看看:

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

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

     1 using UnityEngine;
     2 using System.Collections;
     3 
     4 public class Test1 : MonoBehaviour
     5 {
     6     void Start()
     7     {
     8         OnStart();
     9     }
    10 
    11     protected virtual void OnStart()
    12     {
    13         
    14     }
    15     
    16     void Update()
    17     {
    18         OnUpdate();
    19     }
    20 
    21     protected virtual void OnUpdate()
    22     {
    23         
    24     }
    25 }

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

  • 相关阅读:
    review37
    review36
    review35
    linux 下 安装mysql
    安装yum
    hadoop mapreduce 计算平均气温的代码,绝对原创
    hadoop mapreduce 计算平均气温的代码,绝对原创
    Mysql命令大全
    Mysql命令大全
    约瑟夫问题
  • 原文地址:https://www.cnblogs.com/hammerc/p/4492434.html
Copyright © 2011-2022 走看看