Getting Null Reference Exception for the attack object

The code seems to get passed the “continue” command and execute the attack on a target but it does not find a target (null reference). I have added the combat target component to the enemy and checked over all the code against the github and the tutorial many times. I can’t figure out what’s wrong. Any help would be greatly appreciated.

NullReferenceException: Object reference not set to an instance of an object
RPG.Control.PlayerController.InteractWithCombat () (at Assets/Scripts/Control/PlayerController.cs:28)
RPG.Control.PlayerController.Update () (at Assets/Scripts/Control/PlayerController.cs:12)

PlayerController.cs

using UnityEngine;
using RPG.Movement;
using RPG.Combat;

namespace RPG.Control
{
    public class PlayerController : MonoBehaviour
    {

        private void Update()
        {
            InteractWithCombat();
            InteractWithMovement();
        }

        private void InteractWithCombat()
        {
            RaycastHit[] hits = Physics.RaycastAll(GetMouseRay());
            foreach (RaycastHit hit in hits) 
            {
                CombatTarget target = hit.transform.GetComponent<CombatTarget>();
                if (target == null) continue;

                

                if(Input.GetMouseButtonDown(0))
                {
                    GetComponent<Fighter>().Attack(target);
                }
            }
        }

        private void InteractWithMovement()
        {
            if (Input.GetMouseButton(0))
            {
                MoveToCursor();
            }
        }

        private void MoveToCursor()
        {
            
            RaycastHit hit;
            
            bool hasHit = Physics.Raycast(GetMouseRay(), out hit);
            if (hasHit)
            {
                GetComponent<Mover>().MoveTo(hit.point);
            }
        }

        private static Ray GetMouseRay()
        {
            return Camera.main.ScreenPointToRay(Input.mousePosition);
        }
    }
}

Fighter.cs

using UnityEngine;


namespace RPG.Combat
{
    public class Fighter : MonoBehaviour
    {
        public void Attack(CombatTarget target)
        {
            print("Take that you short, squat peasant!");
        }
    }
}

CombatTarget.cs

using UnityEngine;

namespace RPG.Combat
{
    public class CombatTarget : MonoBehaviour
    {

    }    
}

Line 28 appears to be

GetComponent<Fighter>().Attack(target);

We can exclude target being null, as we’ve already instructed the foreach loop to continue if it doesn’t exist. This leaves us with the Fighter being null.

Make sure there is a Fighter component attached to your Player’s GameObject.

That was it, thank you! I knew I must have missed a step somewhere, just couldn’t pin point it.

It’s a common error. I think we’ve all done it more than a few times.

1 Like

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

Privacy & Terms