Click to move

Why when I try to move my character compiler says NullReferenceException: Object reference not set to an instance of an object error on line 24, I checked it but can’t see the problem.

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

public class ClickToMove : MonoBehaviour {

    private Animator mAnimator;

    private NavMeshAgent mNavMeshAgent;

    private bool mRunning = false;

    // Use this for initialization
    void Start ()
    {
        mAnimator = GetComponent<Animator> ();
        mNavMeshAgent = GetComponent<NavMeshAgent> ();
    }

    // Update is called once per frame
    void Update ()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit hit;

        if (Input.GetMouseButton (0))
        {
            if (Physics.Raycast (ray, out hit, 100))
            {
                mNavMeshAgent.destination = hit.point;
            }
        }

        if (mNavMeshAgent.remainingDistance <= mNavMeshAgent.stoppingDistance) {
            mRunning = false;
        }
        else
        {
            mRunning = true;
        }

        mAnimator.SetBool ("running", mRunning);
    }
}

Do the line numbers coincide with these?

Perhaps you don’t have a camera in the scene which have tag “MainCamera”.
If so, Camera.main will be null.

1 Like