Home > Enterprise >  What is causing this raycast click movement script using NavMeshAgent return a NullReferenceExceptio
What is causing this raycast click movement script using NavMeshAgent return a NullReferenceExceptio

Time:01-11

When I run this script copied from a tutorial, the Unity console consistently returns a NullReferenceException: Object reference not set to an instance of an object. This occurs when I hit right click to tell the object to move. I have made sure that the object has a NavMeshAgent component, but the engine cannot find it.

To clarify, I am not asking what a NullReferenceException is. I am asking why this script returns one, despite that I have given it an object to reference and that object is not empty. In essence I am looking to identify why the reference is finding Null, when it should be finding a NavMeshAgent component.

NavMeshAgent is a component on the Object that the script is attached to.

`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class CharacterMovement : MonoBehaviour
{

    NavMeshAgent agent;

    public float rotateSpeedMovement;
    float rotateVelocity;

    // Start is called before the first frame update
    void Start()
    {
        agent = gameObject.GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        //When pressing RMB
        if(Input.GetMouseButtonDown(1)){
            RaycastHit hit;
        
            //Checking if raycast has hit the navmesh system
            if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit,
            Mathf.Infinity)){

                //have the player move to the point
                agent.SetDestination(hit.point);

                //ROTATION
                Quaternion rotationToLookAt = Quaternion.LookRotation(hit.point - 
                transform.position);
                float rotationY = Mathf.SmoothDampAngle(transform.eulerAngles.y,
                rotationToLookAt.eulerAngles.y,
                ref rotateVelocity,
                rotateSpeedMovement * (Time.deltaTime * 5));

                transform.eulerAngles = new Vector3 (0,rotationY,0);
        
                }
            }
        }
    }`

The object should move to the point clicked, but doesn't. I've tried using a serialised field and using

this.gameObject.GetComponent<NavMeshAgent>();

But I get the same error regardless.

CodePudding user response:

You said the error:

indicates line agent = gameObject.getComponent... if I open the script by clicking the error message.

but I don't think that's the line at all, because gameObject.GetComponent<>() shouldn't throw an exception, it just returns null if the component doesn't exist.

What I suspect is that you've got the script on some other GameObject, and that other GameObject does NOT have an attached NavMeshAgent.

Easy troubleshooting step here to verify:

void Start()
{
    agent = gameObject.GetComponent<NavMeshAgent>();
    if(agent == null)
    {
        Debug.LogErrorFormat("Failed to find a NavMeshAgent on {0}!", gameObject.name);
    }
}

Then see what the name of the thing missing your NavMeshAgent is. I'd bet it's not the thing you think it is!

CodePudding user response:

There are only two variables in your script that could cause your NullReferenceException.

Your class defines one variable which could be agent or Camera.main. Since other comments have ruled out agent being null you likely do not have the MainCamera tag set on your camera thus Camera.main results in your exception.

If that is not the case you should wrap the contents of your if statement with a try/catch to identify the object that does not have agent set.

       if (Input.GetMouseButtonDown(1))
        {
            try
            {
                RaycastHit hit;

                //Checking if raycast has hit the navmesh system
                if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit,
                Mathf.Infinity))
                {

                    //have the player move to the point
                    agent.SetDestination(hit.point);

                    //ROTATION
                    Quaternion rotationToLookAt = Quaternion.LookRotation(hit.point -
                    transform.position);
                    float rotationY = Mathf.SmoothDampAngle(transform.eulerAngles.y,
                    rotationToLookAt.eulerAngles.y,
                    ref rotateVelocity,
                    rotateSpeedMovement * (Time.deltaTime * 5));

                    transform.eulerAngles = new Vector3(0, rotationY, 0);
                    Debug.LogError("hello");

                }
            }
            catch (System.NullReferenceException exception)
            {
                Debug.LogError("This is the object causing the exception", this);
            }
        }

For further reading on debugging NullReferenceExceptions have a look at this guide.

  • Related