Null reference Issue

When I am clicking on Enemy capsule then the game stops and throws a Null reference exception.

Fighter Script :

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

Player Controller Script:

public class PlayerController : MonoBehaviour
{
private void Update()
{
if (InteractWithCombat()) return;
if (InteractWithMovement()) return;
print(“do Nothing”);
}

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

            return true;
        }

        return false;
    }

    private bool 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);
            }

            return true;
        }

        return false;
    }

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

}

Movement Script

public class Mover : MonoBehaviour
{
NavMeshAgent navMeshAgent;
private void Start()
{
navMeshAgent = GetComponent();
}
void Update()
{
UpdateAnimator();
}

    public void MoveTo(Vector3 destination)
    {
        navMeshAgent.destination = destination;
        navMeshAgent.isStopped = false;
    }

    public void Stop()
    {
        navMeshAgent.isStopped = true;
    }
    private void UpdateAnimator()
    {
        Vector3 velocity = navMeshAgent.velocity;
        Vector3 localVelocity = transform.InverseTransformDirection(velocity);
        float speed = localVelocity.z;
        GetComponent<Animator>().SetFloat("ForwardSpeed", speed);
    }
}

Click on the null reference message and in the detail pane of the Console, it should give you the stack trace. The first line of the trace is usually the line that contains the null reference.

For now, copy the contents of the detail pane and paste it here, and it will help me to isolate your error.

Hello Sir Brian

Error is pointing towards Fighter script and line number 15 which “Vector3.Distance” line

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

Ah, I see it now. You’re accessing the target before checking to see if it’s null… in the previous lectures, the target was set in the inspector, and that worked, but now we need to null check it before we check the range.
Create a new method IsInRange()

bool IsInRange()
{
     return Vector3.Distance(transform.position, target.position) < weaponRange;
}

Then remove the bool isInRange on that first line of Fighter.update.
In the If statement, change it to

if(target!=null && !IsInRange())

Because of the short circuit nature of &&, IsInRange() will only be called if the target is not null.

1 Like

Thank you, Mr. Brian working perfectly fine I see there is also an error that pops up in the lecture as well but the game working fine there with the same code why is that?

Difficult to tell without being able to see the details of the NRE, which we don’t see in the video.

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

Privacy & Terms