NullReferenceException in Fighter.cs

Hello @all,

I´m at the point of " Swappable Control Systems" in the course. So, in case of the player reached the “chaseDistance”, the Enemie should attack:

     [SerializeField] float chaseDistance = 5f;

       GameObject player;
       Transform lastKnownPlayerPosition;
       Transform startPosition;
       Fighter fighter;


       private void Start()
       {
           player = GameObject.FindWithTag("Player");
           startPosition = transform;
           fighter = GetComponent<Fighter>();
       }
       private void Update()
       {
           
           if (IsInViewDistance())
           {
                   if (fighter.CanAttack(player))
               {
                   print(name + " greift an!");
                   fighter.Attack(player);                    
               }               
           }
 }      

But, if my player reached the chaseDistance, the console tells me:
“NullReferenceException: Object reference not set to an instance of an object
RPG.Combat.Fighter.Attack (UnityEngine.GameObject combatTarget) (at Assets/Scripts/Combat/Fighter.cs:88)
RPG.Control.AIController.Update () (at Assets/Scripts/Control/AIController.cs:36)”

My “Attack” method looks like in the video:

        public void Attack(GameObject combatTarget)
        {
            if (combatTarget != null)
            {
                GetComponent<ActionScheduler>().StartAction(this);
                target = combatTarget.GetComponent<Health>();
            }
        }

I saw the other NullException about fighter and there solution was to add the Mover.cs to the Enemie. But in my case, the Mover.cs is added to the prefab:

And my player has the Health.cs:

So, what do I miss / made wrong?

Many greetings,
Benjamin

I think it’s the ActionScheduler. You are getting the component and assuming that the result is valid, but it’s null because you removed it from the enemy

You can change it to

if (TryGetComponent<ActionScheduler>(out ActionScheduler scheduler))
{
    scheduler.StartAction(this);
}

This will then only start the action if the ActionScheduler exists

That is strange. The ActionScheduler is assigned to the Character, where the Enimie is created from:

But you are right, the Enemy doesn´t have this:

Thanks for the hint, now it works :slight_smile:

Yes, I saw this in your first screenshots

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms