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.