NullReferenceException error

I am trying to follow a tutorial trying to get bullet holes to work but it says there is an NullReferenceException error on line 49. Here is my code.

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


public class WeaponHandler : MonoBehaviour
{
    public Gun[] loadout;
    public Transform weaponParent;
    public GameObject bulletholePrefab;
    public LayerMask canBeShot;

    private GameObject currentWeapon;

    void Start()
    {
       
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1)) Equip(0);

        if (currentWeapon != null)
        {
            if(Input.GetMouseButtonDown(0))
            {
            Shoot();
            }
        }   
    }

    void Equip(int p_id)
    {
        if (currentWeapon != null) Destroy(currentWeapon);

        GameObject t_newWeapon = Instantiate(loadout[p_id].prefab, weaponParent.position, weaponParent.rotation, weaponParent) as GameObject;
        t_newWeapon.transform.localPosition = Vector3.zero;
        t_newWeapon.transform.localEulerAngles = Vector3.zero;

        currentWeapon = t_newWeapon;
    }

    void Shoot()
    {
        Transform t_spawn = transform.Find("Cameras/JimmyCamera");

        RaycastHit t_hit = new RaycastHit();
        if(Physics.Raycast(t_spawn.position, t_spawn.forward, out t_hit, 1000f, canBeShot))
        {
            GameObject t_newHole = Instantiate(bulletholePrefab, t_hit.point + t_hit.normal * 0.001f, Quaternion.identity) as GameObject;
            t_newHole.transform.LookAt(t_hit.point + t_hit.normal);
            Destroy(t_newHole, 10f);
        }
    }
}

Can anyone please help me fix this error

Looks like Line 46 isn’t finding JimmyCamera. You can check this by adding print(t_spawn); just after Line 46. Post a screencap of your scene’s hierarchy. I’m guessing JimmyCamera isn’t where this code thinks it is.

(Bit of a leap on my part, but try replacing Line 46 with t_spawn = GameObject.Find("Cameras/JimmyCamera");. Might work.)

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

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.

I replaced line 46 with your version but it says “t_spawn doesn’t exist in current context”

Oops. Use this instead:

Transform t_spawn = GameObject.Find("Cameras/JimmyCamera");

Thank you but now it says that it can’t implicitantly convert type UnityEngine.GameObject to UnityEngine.Transform

Yup. My bad again. Use this:

Transform t_spawn = GameObject.Find("Cameras/JimmyCamera").transform;

Awesome thank you

1 Like