[SOLVED] Accessing protected variables from a child class.

I am trying to access the ‘health’ variable that is set in my parent class and trying to use its value in my child class, but I am getting the error ‘NullReferenceException’ on line 23 of my child class (the statement that is trying to access it).

Parent class ‘SpellScript’:

using UnityEngine;
using System.Collections;

public class SpellScript : MonoBehaviour
{
  
        public GameObject projectile;
        public int damage;
        public int manaCost;
      
        public float cooldown;
        public float cooldownRemaining;
        public float weight;
      
        protected internal HealthScript health;

        void Awake ()
        {
                health = gameObject.GetComponent<HealthScript> ();
        }

        public virtual void Activate (Vector2 targetPos)
        {
        }
}

Child class ‘BlizzardScript’:

using UnityEngine;
using System.Collections;

public class BlizzardScript : SpellScript
{
        public int limit;
      
        private Camera cam;
      
        void Awake ()
        {
                cam = Camera.main;
        }

        public override void Activate (Vector2 targetPos)
        {
                Debug.Log ("Blizzard");
                Bounds bounds = cam.OrthographicBounds ();
                float increment = (bounds.max.x - bounds.min.x) / limit;
                for (int i = 0; i <= limit; i++) {
                        Vector2 pos = new Vector2 (increment * i, bounds.max.y);
                        Vector2 topos = new Vector2 (pos.x + 0.5f, bounds.min.y);
                        Debug.Log ("hea" + health.isEnemy);
                        //ProjectileScript.CreateProjectile (projectile, damage, pos, topos, health.isEnemy);
                }
  
        }
}

Bump

when is Activate called relative to Awake? If you’re calling it from another script on Awake, this script might not have been initialized yet.

You also have Awake defined in both the child class and the parent class. But they aren’t marked to override. Unity will use the first method it finds on reflection… which will be the child class. Mark the parent classes Awake to be protected virtual, and override it in the child class. Make sure to call ‘base.Awake’ when you do so.

Are you sure that a HealthScript is added to the same GameObject?

1 Like

Thanks. Making the parent method protected virtual and the child one protected override along with calling base.Awake() fixed the problem.