NullReferenceException: Object reference not set to an instance of an object HandGun.playerMove()

NullReferenceException: Object reference not set to an instance of an object
HandGun.playerMove () (at Assets/Scripts/Rifles/HandGun.cs:152)
HandGun.Update () (at Assets/Scripts/Rifles/HandGun.cs:92)
here is the code

private void Update()
   {

      if(HandgunActive == true)
      {
         animator.runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("GunAnimator");
      }


      OnSurface = Physics.CheckSphere(surfaceCheck.position, surfaceDistance, surfaceMask);

      if (OnSurface && velocity.y < 0)
      {
         velocity.y = -2f;
      }
    
      //gravity
      velocity.y += gravity * Time.deltaTime;
      cC.Move(velocity * Time.deltaTime);
    
      playerMove();
      Jump();
      Sprint();
      
      if (setReloading) 
         return;

      if (presentAmmunition <= 0)
      {
         StartCoroutine(Reload());
         return;
      }
      
      if(isMoving == false) 
      {
         if (Input.GetButton("Fire1") && Time.time >= nextTimeToShoot)
         {
            animator.SetBool("Shoot", true);
            nextTimeToShoot = Time.time + 1f / fireCharge;
            Shoot();
         }
         else
         {
            animator.SetBool("Shoot", false);
         }
      }
   }
   
   

   void playerMove()
   {
      float horizontal_axis = Input.GetAxisRaw("Horizontal");
      float vertical_axis = Input.GetAxisRaw("Vertical");
      

      Vector3 direction = new Vector3(horizontal_axis, 0f, vertical_axis).normalized;

      if (direction.magnitude >= 0.1f)
      {
         animator.SetBool("WalkForward", true);
         animator.SetBool("RunForward", false);
         
      
         float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + playerCamera.eulerAngles.y;
         float angle = Mathf.SmoothDampAngle(PlayerTransform.eulerAngles.y, targetAngle, ref turnCalmVelocity, turnCalmTime);
         PlayerTransform.rotation = Quaternion.Euler(0f, targetAngle, 0f);

         Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
         cC.Move(moveDirection.normalized * playerSpeed * Time.deltaTime);
         jumpRange = 0f;
         isMoving = true;
         handgun2.isMoving = true;
      }
      else
      {
         animator.SetBool("WalkForward", false);
         animator.SetBool("RunForward", false);
         jumpRange = 1f;
         isMoving = false;
         handgun2.isMoving = false;
      }
   }
   
   void Jump()
   {
      if (Input.GetButtonDown("Jump") && OnSurface)
      {
         animator.SetBool("IdleAim", false);
         animator.SetTrigger("Jump");
         velocity.y = Mathf.Sqrt(jumpRange * -2 * gravity);
      }
      else
      {
         animator.SetBool("IdleAim", true);
         animator.SetTrigger("Jump");  
      }
   }

   void Sprint()
   {
      if (Input.GetButton("Sprint") && Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow) && OnSurface)
      {
         float horizontal_axis = Input.GetAxisRaw("Horizontal");
         float vertical_axis = Input.GetAxisRaw("Vertical");

         Vector3 direction = new Vector3(horizontal_axis, 0f, vertical_axis).normalized;

         if (direction.magnitude >= 0.1f)
         {
            animator.SetBool("WalkForward", false);
            animator.SetBool("RunForward", true);
            
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + playerCamera.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(PlayerTransform.eulerAngles.y, targetAngle, ref turnCalmVelocity, turnCalmTime);
            PlayerTransform.rotation = Quaternion.Euler(0f, targetAngle, 0f);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            cC.Move(moveDirection.normalized * playerSprint * Time.deltaTime);
            jumpRange = 0f;
            isMoving = true;
            handgun2.isMoving = true;
         }
         else
         {
            animator.SetBool("WalkForward", true);
            animator.SetBool("RunForward", false);
            jumpRange = 1f;
            isMoving = false;
            handgun2.isMoving = false;
         }
      }
   }

   void Shoot()
   {
      if (mag == 0)
      {
         //show ammo out text/ui

         StartCoroutine(ShowAmmoOut());
         return;
      }
      {
         
      }

      presentAmmunition--;

      if (presentAmmunition == 0)
      {
         mag--;
      }
      muzzleSpark.Play();
      RaycastHit hitInfo;

      if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hitInfo, shootingRange))
      {
         Debug.Log(hitInfo.transform.name);
         
         Object obj = hitInfo.transform.GetComponent<Object>();
      
         if (obj != null)
         {
            obj.objectHitDamage(giveDamage);
            GameObject metalEffectGo = Instantiate(metalEffect, hitInfo.point, Quaternion.LookRotation(hitInfo.normal));
            Destroy(metalEffectGo, 1f);
         }
      }
   }

You have not provided all of the code so nobody can directly help you, as the numbers in your stack trace do not align with what we see.

You need to understand what null reference exceptions are and how to fix them.

1 Like

Sir here is the whole script in which I got errors,

using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UIElements;
using Cursor = UnityEngine.Cursor;

public class HandGun : MonoBehaviour
{
   
   //RIFLE MOVEMENT var (VARIABLES)
   
   [Header("Player Movement")] 
   public float playerSpeed = 1.1f;
   public float playerSprint = 5f;

   [Header("Player Animator & Gravity")] 
   public CharacterController cC;
   public float gravity = -9.81f;
   public Animator animator;
  
   [Header("Player Script Camera")] 
   public Transform playerCamera;

   [Header("Player Jumping & Velocity")] 
   public float jumpRange = 1f;
   public float turnCalmTime = 0.1f;
   float turnCalmVelocity;
   Vector3 velocity;
   public Transform surfaceCheck;
   private bool OnSurface;
   public float surfaceDistance = 0.4f;
   public LayerMask surfaceMask;
   
   
   //RIFLE SHOOTING VAR (VARIABLES)
   
   [Header("Rifle Things")] 
   public Camera cam;
   public float giveDamage = 10f;
   public float shootingRange = 100f;
   public float fireCharge = 10f;
   private float nextTimeToShoot = 0f;
   public Transform hand;
   public Transform PlayerTransform;
   public HandGun2 handgun2;
   public bool isMoving;

   [Header("Rifle Ammunition and Reloading")]
   private int maximumAmmunition = 25;
   public int mag = 10;
   private int presentAmmunition;
   public float reloadingTime = 4.3f;
   private bool setReloading = false;

   [Header("Rifles Effect")] 
   public ParticleSystem muzzleSpark;
   public GameObject metalEffect;

   [Header("Sound & UI")] 
   public GameObject AmmoOutUI;
   bool HandgunActive = true;
   
   private void Awake()
   {
      transform.SetParent(hand);
      Cursor.lockState = CursorLockMode.Locked;
      presentAmmunition = maximumAmmunition;
   }

   private void Update()
   {

      if(HandgunActive == true)
      {
         animator.runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("GunAnimator");
      }


      OnSurface = Physics.CheckSphere(surfaceCheck.position, surfaceDistance, surfaceMask);

      if (OnSurface && velocity.y < 0)
      {
         velocity.y = -2f;
      }
    
      //gravity
      velocity.y += gravity * Time.deltaTime;
      cC.Move(velocity * Time.deltaTime);
    
      playerMove();
      Jump();
      Sprint();
      
      if (setReloading) 
         return;

      if (presentAmmunition <= 0)
      {
         StartCoroutine(Reload());
         return;
      }
      
      if(isMoving == false) 
      {
         if (Input.GetButton("Fire1") && Time.time >= nextTimeToShoot)
         {
            animator.SetBool("Shoot", true);
            nextTimeToShoot = Time.time + 1f / fireCharge;
            Shoot();
         }
         else
         {
            animator.SetBool("Shoot", false);
         }
      }
   }
   
   

   void playerMove()
   {
      float horizontal_axis = Input.GetAxisRaw("Horizontal");
      float vertical_axis = Input.GetAxisRaw("Vertical");
      

      Vector3 direction = new Vector3(horizontal_axis, 0f, vertical_axis).normalized;

      if (direction.magnitude >= 0.1f)
      {
         animator.SetBool("WalkForward", true);
         animator.SetBool("RunForward", false);
         
      
         float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + playerCamera.eulerAngles.y;
         float angle = Mathf.SmoothDampAngle(PlayerTransform.eulerAngles.y, targetAngle, ref turnCalmVelocity, turnCalmTime);
         PlayerTransform.rotation = Quaternion.Euler(0f, targetAngle, 0f);

         Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
         cC.Move(moveDirection.normalized * playerSpeed * Time.deltaTime);
         jumpRange = 0f;
         isMoving = true;
         handgun2.isMoving = true;
      }
      else
      {
         animator.SetBool("WalkForward", false);
         animator.SetBool("RunForward", false);
         jumpRange = 1f;
         isMoving = false;
         handgun2.isMoving = false;
      }
   }
   
   void Jump()
   {
      if (Input.GetButtonDown("Jump") && OnSurface)
      {
         animator.SetBool("IdleAim", false);
         animator.SetTrigger("Jump");
         velocity.y = Mathf.Sqrt(jumpRange * -2 * gravity);
      }
      else
      {
         animator.SetBool("IdleAim", true);
         animator.SetTrigger("Jump");  
      }
   }

   void Sprint()
   {
      if (Input.GetButton("Sprint") && Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow) && OnSurface)
      {
         float horizontal_axis = Input.GetAxisRaw("Horizontal");
         float vertical_axis = Input.GetAxisRaw("Vertical");

         Vector3 direction = new Vector3(horizontal_axis, 0f, vertical_axis).normalized;

         if (direction.magnitude >= 0.1f)
         {
            animator.SetBool("WalkForward", false);
            animator.SetBool("RunForward", true);
            
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + playerCamera.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(PlayerTransform.eulerAngles.y, targetAngle, ref turnCalmVelocity, turnCalmTime);
            PlayerTransform.rotation = Quaternion.Euler(0f, targetAngle, 0f);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            cC.Move(moveDirection.normalized * playerSprint * Time.deltaTime);
            jumpRange = 0f;
            isMoving = true;
            handgun2.isMoving = true;
         }
         else
         {
            animator.SetBool("WalkForward", true);
            animator.SetBool("RunForward", false);
            jumpRange = 1f;
            isMoving = false;
            handgun2.isMoving = false;
         }
      }
   }

   void Shoot()
   {
      if (mag == 0)
      {
         //show ammo out text/ui

         StartCoroutine(ShowAmmoOut());
         return;
      }
      {
         
      }

      presentAmmunition--;

      if (presentAmmunition == 0)
      {
         mag--;
      }
      muzzleSpark.Play();
      RaycastHit hitInfo;

      if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hitInfo, shootingRange))
      {
         Debug.Log(hitInfo.transform.name);
         
         Object obj = hitInfo.transform.GetComponent<Object>();
      
         if (obj != null)
         {
            obj.objectHitDamage(giveDamage);
            GameObject metalEffectGo = Instantiate(metalEffect, hitInfo.point, Quaternion.LookRotation(hitInfo.normal));
            Destroy(metalEffectGo, 1f);
         }
      }
   }

   IEnumerator Reload()
   {
      playerSpeed = 0f;
      playerSprint = 0f;
      setReloading = true;
      Debug.Log("Reloading....");
      animator.SetBool("Reload", true);
      yield return new WaitForSeconds(reloadingTime);
      Debug.Log("Done Reloading....");
      animator.SetBool("Reload", false);
      presentAmmunition = maximumAmmunition;
      playerSpeed = 1.1f;
      playerSprint = 5f;
      setReloading = false;
   }

   IEnumerator ShowAmmoOut()
   {
      AmmoOutUI.SetActive(true);
      yield return new WaitForSeconds(5f);
      AmmoOutUI.SetActive(false);
   }
}

Then as you should be able to understand and fix via the info in the link I sent, handgun2 is not assigned. It looks like you must not have assigned it in the inspector, or have destroyed it

1 Like

ohh I see well thanks a lot sir for giving me your precious time I’m very thankful to you

NullReference is the single most common error while programming. Fixing it is always the same.

  • 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

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:

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

The basic 3 steps outlined above are:

  1. Identify what is null
  2. Identify why it is null
  3. 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:

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

Here is an analogy of a null reference:

  • I give you an empty cookie jar
  • I tell you to take a cookie from the jar

Your job is to identify which jar is empty, find out why it is empty, and fix that.

1 Like

Thanks a lot, sir these steps are really helpful to me…