inheritance - using base class member variables

Hello,
I having problems understanding and using the member variables of a class that inherits from MonoBehavior.

I have class A that inherits from MonoBehavior:

  class A: MonoBehaviour
    {
        protected char[] code;

        /// this method uses member variable "code"
        public virtual void AddItem(uint pos, char letter)   
        {
             if (code[pos] == letter && code.Length < 4)
             {
                  Debug.log("You WIn");
             }
         }
    }

and class B that inherits from class A:

public class B: A
{
    void Start () {
        code = new char[] { 'A', 'A', 'D', 'W' };  // Here I initialize the member variable "code" 
    }
}

Class B is attached to a game object (GO) that has a component (myClassB).

public class GO : MonoBehaviour
{
    public B myClassB;

    void OnTriggerEnter(Collider other)
    {
        // here it calls AddItem, inherited method. it should call A::AddItem
        myClassB.AddItem(pos,label);  
    }
}

In game, when my GO receives an event it calls myClassB.AddItem, which is the method inherited from the base class A. However, I got a NullReferenceException in the AddItem method because I havent initialized the member variable “code”.
I thought the Start method in class B would do that.

I set a protected member variable “id” on the parent equals to 0. Later, the Start method of the derived class I increased that value to 1. But when the event in the GO calls myClassB.AddItem, I noticed the parent “id” variable gets back to 0. Like the GO was initialized entirely.

I hope it makes sense and you guys can give me a hand on what is happening.

Try putting a Debug.Log in class B’s Start method to see if it is being called.


Got a feeling you may need to have ‘public virtual void Start()’ in class A for class B to override.

Hi!

I put the Debug.Log in class B’s Start method and indeed It’s called. Unfortunately, it did not change the outcome.

Also, I tried initializing the member variable in the Awake method of class B, but same error.

 void Awake () {
        
        code = new char[] { 'A', 'A', 'D', 'W' };
        Debug.Log("B::Awake");
        
    }

Also, I tried using:

 public virtual void Start()

In the base class, but it didnt work either.

What I’m trying to do seems logic from a C++ point of view. I dont know if inheritance works different in C sharp.

I appreciate the help.