- Home /
Base class variables not initialized for sub class?
I have a base class for all creatures that all share some variables.
public class Creature : MonoBehaviour {
[HideInInspector] public Rigidbody rb;
[HideInInspector] public Animator anim;
[HideInInspector] public Health health;
public LayerMask groundLayer = 1;
public bool isGrounded;
void Awake () {
rb = GetComponent<Rigidbody>();
anim = GetComponent<Animator>();
health = GetComponent<Health>();
}
void FixedUpdate(){
isGrounded = Physics.Raycast(transform.position + (Vector3.up * 0.02f), Vector3.down, 0.2f, groundLayer);
}
}
Subclasses like Player/Enemy/NPC therefore derive from Creature so all the variables are accessable, but when I want to use rb/anim/health I always get a NullReferenceException.
I don't get it since I initialized the components in the base class.
Answer by Bunny83 · Aug 21, 2017 at 03:30 PM
Are you sure you don't implement an Awake method in the sub class? If so Unity won't call the Awake of the base class. If you want to use inheritance you may want to declare your Awake as "protected virtual" instead of "private". So when a child class need to extend the Awake functionality you can properly override it and call the base version.
All my subclasses have an Awake method. So I added "protect virtual" in the baseclass and "protected override" in the childs' Awake, but it dont worked somehow.
Ah never$$anonymous$$d. I had to call base.Awake() in the children class.