Protected variable is assigned in parent but null in child
I'm trying to set up a simple inheritance but I'm running into an issue. Here's a simplified version of my setup:
public class BaseClass : MonoBehaviour
{
protected DialogueManager dialogueManager;
public virtual void Awake ()
{
dialogueManager = GetComponent<DialogueManager>();
print(dialogueManager);
}
}
public class ChildClass : BaseClass
{
public override void Awake()
{
print(dialogueManager);
}
}
Both scripts are attached to the same object, and I confirmed that ChildClass
's Awake
is executing after BaseClass
(manually defined in Unity's Execution Order). The print statement in BaseClass
shows that dialogueManager
is assigned, but the one in ChildClass
returns null.
Answer by Vicarian · Jun 14, 2018 at 11:26 PM
Use
base.Awake();
In the child class's Awake() method.
Thanks! This works, but can you explain why calling BaseClass.Awake()
manually doesn't work? I had tested this before, and if I do a GetComponent<BaseClass>().Awake()
before print(dialogue$$anonymous$$anager)
, it prints null. But it works when I replace the line with base.Awake()
.
If you access the BaseClass using GetComponent directly, you're telling that instance to run its Awake method, which doesn't affect the child. base.Awake() follows the inheritance chain and does affect the construction of the child class.