"NullReferenceException: Object reference not set to an instance of an object" Error

Hello, I am working on a game using a tutorial that is kind of old (eight years ago) just for learning and practice purposes, a light gun shooter. The tutorial I am using is from a youtuber PushyPixels, so credits go to him.

Video:
__https://www.youtube.com/watch?v=u_SvMqFjNmI__
__ __

Most of the code I tried out was working up until the clicking in other places, which cause this error:

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

Here is my code:

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

public class ShotPOS : MonoBehaviour
{

    public Rigidbody bullet;
    public float force = 10.0f;
    public ForceMode forceMode;
 

    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetMouseButtonDown(0))

        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Vector3 spawnPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane + 1.0f));



            Rigidbody instance = Instantiate(bullet, transform.position, Quaternion.LookRotation(ray.direction)) as Rigidbody;
            instance.AddForce(transform.forward * force, forceMode);
        }
   
   
    }
}

The Vector3 spawnPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane + 1.0f));
is what’s causing the issue. If anyone can please help, let me know.

And yes, I am very new to this, just using tutorials to learn how most things work.

Make sure that the camera in your scene is assigned to the “MainCamera” tag. Calling Camera.main is essentially the same as calling GameObject.FindObjectWithTag(“MainCamera”).

Which means that if there is no camera in your scene with the “MainCamera” tag then Camera.main will not return a camera and thus you get a null reference exception.

1 Like

It actually does not even remotely matter what you are doing, and you actually never need to post for a nullref!

The reason is the answer is always the same… ALWAYS.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that