Search Unity

Inheritance and polymorphism

Discussion in 'Scripting' started by Maraku Mure, May 29, 2015.

  1. Maraku Mure

    Maraku Mure

    Joined:
    May 2, 2015
    Posts:
    28
    Hello...
    I have a question.

    I have two classes and two functions:

    Code (CSharp):
    1. public class BaseClass : MonoBehaviour {
    2.           public void Awake () {
    3.                            //initializing some variable
    4.           }
    5. }
    6.  
    7. public class ClassDerivated : BaseClass {
    8.           new void Awake () {
    9.                      base.Awake();
    10.                      Debug.Log ("I have initialized variables and now I print");
    11.           }
    12.  
    13. }
    The BaseClass "Awake ()" function in order to be called with "base" keywork in the derivated class, has to be public? What if I want to set this function private?

    In my project I have a base function in the base class and a polymorphed in the derivated class which does the previous things more updating a text item and I would like to keep things separated and the first function (the one of the BaseClass) private....how could I do?
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Make Awake protected virtual in BaseClass and protected override in ClassDerivated. What you have isn't actually inheriting the functionality of Awake
     
  3. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
    You have to make your method protected, this way it is visible to the derived classes

    Code (CSharp):
    1. public class BaseClass : MonoBehaviour {
    2.           protected virtual void Awake () {
    3.                            //initializing some variable
    4.           }
    5. }
    6. public class ClassDerivated : BaseClass {
    7.           protected override void Awake () {
    8.                      base.Awake();
    9.                      Debug.Log ("I have initialized variables and now I print");
    10.           }
    11. }
     
    Last edited: May 29, 2015
  4. Maraku Mure

    Maraku Mure

    Joined:
    May 2, 2015
    Posts:
    28
    Thank you guys!
     
  5. LiberLogic969

    LiberLogic969

    Joined:
    Jun 29, 2014
    Posts:
    138
    As long as the virtual method isn't private the inherited class will see it.