Move within Range - Null reference

Hello, I am also running into this error, and I can see from past posts that this is due to not picking a target first. However, the video shows that you can continue to progress even with the error, but in my game, I cannot move my character to test functionality, the game just simply does not let me play when i click the play button. I don’t know if its due to the later version of Unity that is being used (I am using 2019.4.5f1).

I believe I have followed the course correctly and have also tried adding in the code from the repository. Here is the code for my Fighter.cs script. I am new to coding and would like to not stray too far from the examples in the course.
Any suggestions for moving forward?

Thanks!

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;
        }
    }

}

The problem is that the isInRange is being calculated every frame whether target is null or not.

There are two possible fixes…

  • open Update() with if(target==null) return;
  • Refactor the check to make a new function IsInRange() that checks the distance.
bool IsInRange()
{
     return Vector3.Distance(transform.position, target.position) < weaponRange;
}

void Update()
{
     if(target!=null && !IsInRange())
1 Like

Thank you!!!

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

Privacy & Terms