NullReferenceException: Object not set to an Instance of an Object Issue

Hi, I’m having trouble finding the cause of this null reference exception:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Movement;

namespace RPG.Combat
{
    public class Fighter : MonoBehaviour
    {
        [SerializeField]
        float weaponRange = 2f;
        private Transform target;

        private void Update()
        {
            bool isInRange = Vector3.Distance(target.position, target.position) < weaponRange;
            if(target != null && !isInRange)
            {
                GetComponent<Mover>().MoveTo(target.position);
            }
            else
            {
                GetComponent<Mover>().Stop();
            }
        }
        public void Attack(CombatTarget combatTarget)
        {
            target = combatTarget.transform;
        }

        public void Cancel()
        {
            target = null;
        }

    }
}

The error says it’s on line 16 which, if I counted correctly, is this line. It suggests that your fighter does not have a Mover script attached to it

Line 16 is actually

bool isInRange = Vector3.Distance(target.position, target.position) < weaponRange;

The trouble is that the target isn’t always not null.
Start the method with

if(target==null) return;

and the error should go away.

That being said, there is another error on the line that is harder to diagnose. Right now, you’re comparing the target’s position to the target’s position, which is always a distance of 0. You want to compare the transform position and target position. Change that line to:

bool isInRange = Vector3.Distance(transform.position, target.position) < weaponRange;
1 Like

Thanks @Brian_Trotter. I did count it wrong, then.

It’s hard to count when it’s not formatted correctly. I fixed the formatting, and then the count was easy. :slight_smile:

thanks a bunch, really appreciate ya

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

Privacy & Terms