Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to Overriding Monobehaviour Messages ? (Solved)

Discussion in 'Scripting' started by PJRM, Mar 10, 2015.

  1. PJRM

    PJRM

    Joined:
    Mar 4, 2013
    Posts:
    303
    Hello Unity!

    Guess the title says everything!
    Here what I'm trying to say:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class A : MonoBehaviour {
    4.   void Update () {
    5.     Debug.log("Main class");
    6.   }
    7. }
    And my second class inherits from it:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class B : A {
    4.   // TODO: how to do this override in the messages?
    5.   protected override void Update () {
    6.     base.Update() // <= this here doesn't work.
    7.     Debug.log("B as A");
    8.   }
    9. }
    How to override the monobehaviour messages ?
     
  2. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    Make the update in class A virtual:
    Code (CSharp):
    1. public class A : MonoBehaviour
    2. {
    3.     // Update is called once per frame
    4.     protected virtual void Update()
    5.     {
    6.         Debug.Log("Base class A");
    7.     }
    8. }
    9.  
    10. public class B : A
    11. {
    12.     // Update is called once per frame
    13.     protected override void Update()
    14.     {
    15.         base.Update();
    16.         Debug.Log("Child class B");
    17.     }
    18. }
    Verified with Unity 5, I expect it also works with 4.6
     
  3. PJRM

    PJRM

    Joined:
    Mar 4, 2013
    Posts:
    303
    Thank you so much!