NullReferenceEx

Hey!

Bottom Line Up Front:

Keep getting a Null Reference Expection:

NullReferenceException: Object reference not set to an instance of an object
Movement.Update () (at Assets/Scripts/Player/Movement.cs:96)

I have no idea what object I’m missing a reference for. The line tags 96:
Ray ray = cam.ScreenPointToRay(Input.mousePosition);

Has no objects attached to it? Is there something I’m missing? I’m just trying to get my Player to focus on something I left click.

I have an interactableLayer and I have an interactable script which I’ve attached to a box. I will include it in the code after my movement code.

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

public class Movement : MonoBehaviour
{

    NavMeshAgent agent;
    public LayerMask groundLayer;
    public LayerMask enemyLayer;
    public LayerMask interactableLayer;
    public float rotateSpeedMovement = 0.01f;
    float rotateVelocity;
    public Interactable focus;
    Camera cam;                // Reference to our camera

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

    // Update is called once per frame
    void Update()
    {
        //if (EventSystem.current.IsPointerOverGameObject())
            //return;
        //When Right Button Pushed
        if (Input.GetMouseButtonDown(1))
        {
            RaycastHit hit;

            //Check if the raycast shot hits something that uses the nav mesh system.
            if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, groundLayer))
            {

                //MOVEMENT
                //Have the player move to the raycast/hit 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);


            }
            //This should be if you target an enemy
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity,enemyLayer))
            {

                //MOVEMENT
                //Have the player move to the raycast/hit 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);


            }
            //This is for InteractableObjects
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, interactableLayer))
            {

                //MOVEMENT
                //Have the player move to the raycast/hit 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);


            }
        }
        //When left button is pushed
        if (Input.GetMouseButtonDown(0))
        {
            // Shoot out a ray
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            // If we hit
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, interactableLayer))
            {
                SetFocus(hit.collider.GetComponent<Interactable>());
            }

        }
        //Escape Key being pushed
        if (Input.GetKey(KeyCode.Escape))
        {
            RemoveFocus();
        }
    }
    //Method for focusing item/player
    void SetFocus (Interactable newFocus)
    {
        focus = newFocus;
    }
    //Method for removing focus
    void RemoveFocus()
    {
        focus = null;
    }
}

My Interactable code:

using UnityEngine;

public class Interactable : MonoBehaviour
{
    public float radius = 3f;

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}

Any help provided I would be greatful. Thank you!

Looking at your code, it doesn’t look as if you ever assign anything to ‘cam’, hence why you’re getting a null ref error.

I see most else the time you use the statically available Camera.main, except that one time where you use your private ‘cam’ field. Either you assign something to ‘cam’ (perhaps by using Camera.main), or you just use Camera.main in its place.

1 Like

You declared a private variable in line 16:

Camera cam;                // Reference to our camera

You never assigned any value to this variable and since it’s private and not marked as serializable it can’t be set through the inspector. Just adding the comment “Reference to our camera” does not magically assign a value to the variable. You really couldn’t spot that? The cam variable is the only thing in the line that could be null.

1 Like

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

1 Like

Thank you for the explanation. That worked!

Nope, just a big, fat, stupid, idiot I guess.

Thank you, I will ensure to follow these steps before posting in the future. Much appreciated.

2 Likes