NullReferenceException: Object reference not set to an instance of an object

So the error seems to be on Line 16?

I Googled NullReferenceExceptions and they were explained as when a variable is not assigned properly, or to null. But in this case I see the bool IsInRange is assigned properly?

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


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

        Transform target;

        private void Update() {
            bool isInRange = Vector3.Distance(transform.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;
        }
    }
}
1 Like

IsInRange actually can’t be null, as it’s a boolean value. It can only be true or false. The problem here is that the target may be null, but we’re still trying to check it’s position.
Try putting the target test first, then calculating the range:

if(!target) return; //ensures we don't work on a null target.
bool isInRange = Vector3.Distance(transform.position, target.position);
if(!isInRange)
//remainder of method
3 Likes

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

Privacy & Terms