How to fix null reference exception problem

NullReferenceException: Object reference not set to an instance of an object
Player.PlayerController.ApplyMovement () (at Assets/Scripts/Player/PlayerController.cs:149)
Player.PlayerController.FixedUpdate () (at Assets/Scripts/Player/PlayerController.cs:91)

NullReferenceException: Object reference not set to an instance of an object
Player.PlayerController.Jumpin () (at Assets/Scripts/Player/PlayerController.cs:312)
Player.PlayerController.Update () (at Assets/Scripts/Player/PlayerController.cs:101)

How can ı fix this problem. İt suddenly started. Code was fine until today. Now in game it is not working.Thanks for help.

using System;
using ProInput.Scripts;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Player {

    public class PlayerController : MonoBehaviour {

        Animator animator;
        public bool Run;
        public bool RunningJump;
        public AudioClip _soundd;    // this lets you drag in an audio file in the inspector
        public AudioSource audioo;

        void Awake()
        {
            audioo = audioo; //oadds an AudioSource to the game object this script is attached to
            audioo.playOnAwake = false;
            audioo.clip = _soundd;
            audioo.Stop();
            Run = false;
            animator = GetComponent<Animator>();
        }

        [Header("Movement")]
        public float movementSpeed;
        public float Accelaration;
        public float airMovementSpeed;
        public float maxSpeed;

        [Header("Friction")]
        public float friction;
        public float airFriction;

        [Header("Rotation")]
        public float rotationSensitivity;
        public float rotationBounds;

        [Header("Gravity")]
        public float extraGravity;

        [Header("Ground Detection")]
        public LayerMask whatIsGround;
        public float checkYOffset;
        public float checkRadius;
        public float groundTimer;

        [Header("Jumping")]
        public float jumpForce;
        public float jumpCooldown;

        [Header("Data")]
        public Camera playerCamera;
        public Transform playerCameraHolder;
        public Rigidbody playerRigidBody;

        private InputObject _forwardsInput;
        private InputObject _backwardsInput;
        private InputObject _leftInput;
        private InputObject _rightInput;
        private InputObject _jumpInput;
        private InputObject _runInput;

        private float _xRotation;
        private float _yRotation;
        private float _grounded;
        private bool _realGrounded;
        private float _jumpCooldown;

        private void Start() {


            _forwardsInput = new InputObject("Forwards", Key.W);
            _backwardsInput = new InputObject("Backwards", Key.S);

            _runInput = new InputObject("run", Key.LeftShift  );

            _leftInput = new InputObject("Left", Key.A);
            _rightInput = new InputObject("Right", Key.D);
            _jumpInput = new InputObject("Jump", Key.Space);
        }

        private void FixedUpdate() {
            GroundCheck();
            ApplyMovement();
            ApplyFriction();
            ApplyGravity();
            RunMovement();
            Movement();
        }

        private void Update() {
            Rotation();
            Jumping();
            Jumpin();
            RollJumping();
        }

        private void GroundCheck() {
            _grounded -= Time.fixedDeltaTime;
            var colliderList = new Collider[100];
            var size = Physics.OverlapSphereNonAlloc(transform.position + new Vector3(0, checkYOffset, 0), checkRadius, colliderList, whatIsGround);
            _realGrounded = size > 0;
            if (_realGrounded)
                _grounded = groundTimer;



        }
        private void Movement()
        {
            if (_realGrounded==false)

            {
                var axis = new Vector2(
               (_leftInput.IsPressed ? -1 : 0) + (_rightInput.IsPressed ? 1 : 0),


               (_backwardsInput.IsPressed ? -1 : 0) + (_forwardsInput.IsPressed ? 1 : 0)
           ).normalized;

                var speed = _realGrounded ? movementSpeed : airMovementSpeed;

                var vertical = axis.y * speed * Time.fixedDeltaTime * transform.forward;


                var horizontal = axis.x * speed * Time.fixedDeltaTime * transform.right;

                if (CanApplyForce(vertical, axis))
                    playerRigidBody.velocity += vertical;

                if (CanApplyForce(horizontal, axis))
                    playerRigidBody.velocity += horizontal;

            }
        }
        private void ApplyMovement() {




            var axis = new Vector2(
                (_leftInput.IsPressed ? 0 : 0) + (_rightInput.IsPressed ? 0 : 0),



                (_backwardsInput.IsPressed ? -1 : 0) + (_forwardsInput.IsPressed ? 1 : 0)
            ).normalized;


            var speed = _realGrounded ? movementSpeed : airMovementSpeed;

            var vertical = axis.y * speed * Time.fixedDeltaTime * transform.forward;


            var horizontal = axis.x * speed * Time.fixedDeltaTime * transform.right;

            if (CanApplyForce(vertical, axis))
                playerRigidBody.velocity += vertical;

            if (CanApplyForce(horizontal, axis))
                playerRigidBody.velocity += horizontal;
        }

        private void RunMovement()
        {

            if (this.animator.GetCurrentAnimatorStateInfo(0).IsName("Run"))
            {
                var axis = new Vector2(
                (_leftInput.IsPressed ? 0 : 0) + (_rightInput.IsPressed ? 0 : 0),


                (_leftInput.IsPressed ? 0 : 0) + (_runInput.IsPressed ? 2 : 0)
            ).normalized;








                var speed = _realGrounded ? Accelaration : airMovementSpeed;

                var vertical = axis.y * speed * Time.fixedDeltaTime * transform.forward;

                var horizontal = axis.x * speed * Time.fixedDeltaTime * transform.right;


                if (CanApplyForce(vertical, axis))
                    playerRigidBody.velocity += vertical;



                if (CanApplyForce(horizontal, axis))
                    playerRigidBody.velocity += horizontal;

            }


      }

        private void ApplyFriction() {
            var vel = playerRigidBody.velocity;
            var target = _realGrounded ? friction : airFriction;
            vel.x = Mathf.Lerp(vel.x, 0f, target * Time.fixedDeltaTime);
            vel.z = Mathf.Lerp(vel.z, 0f, target * Time.fixedDeltaTime);
            playerRigidBody.velocity = vel;
        }

        private void Rotation() {
            Cursor.lockState = CursorLockMode.Locked;
            var mouseDelta = Mouse.current.delta.ReadValue();

            _xRotation -= mouseDelta.y * rotationSensitivity;
            _xRotation = Mathf.Clamp(_xRotation, -rotationBounds, rotationBounds);
            _yRotation += mouseDelta.x * rotationSensitivity;

            transform.rotation = Quaternion.Euler(0, _yRotation, 0);
            playerCameraHolder.localRotation = Quaternion.Euler(_xRotation, 0, 0);
        }

        private void ApplyGravity() {
            var vel = playerRigidBody.velocity;
            vel.y -= Mathf.Abs(vel.y) * Time.fixedDeltaTime * extraGravity;
            playerRigidBody.velocity = vel;
        }

        private void Jumping()
        {


            if (this.animator.GetCurrentAnimatorStateInfo(0).IsName("Crouch İdle"))

            {
                Run = true;


                _jumpCooldown -= Time.deltaTime;
            if (!(_grounded >= 0) || !(_jumpCooldown <= 0) || !_jumpInput.IsDown) return;

                audioo.Play();


                animator.SetBool("Run", true);

                var vel = playerRigidBody.velocity;
                        vel.y = jumpForce;
                        playerRigidBody.velocity = vel;
                        _jumpCooldown = jumpCooldown;
                    }
                }

                private void  RollJumping()
                  {
                    if (this.animator.GetCurrentAnimatorStateInfo(0).IsName("RollJump"))

                    {
                        Run = true;


                        _jumpCooldown -= Time.deltaTime;
                    if (!(_grounded >= 0) || !(_jumpCooldown <= 0)) return;

                        audioo.Play();


                        animator.SetBool("Run", true);

                        var vel = playerRigidBody.velocity;
                                vel.y = jumpForce;
                                playerRigidBody.velocity = vel;
                                _jumpCooldown = jumpCooldown;
                            }
                        }

      private void  Jumpin()
        {

            if (this.animator.GetCurrentAnimatorStateInfo(0).IsName("Run"))

            {


                _jumpCooldown -= Time.deltaTime;
                if (!(_grounded >= 0) || !(_jumpCooldown <= 0) || !_jumpInput.IsDown) return;


                audioo.Play();

                var vel = playerRigidBody.velocity;
                vel.y = jumpForce;
                playerRigidBody.velocity = vel;
                _jumpCooldown = jumpCooldown;
            }
        }

Null reference does not even require ONE form post because the answer to fix it is ALWAYS the same. And yet you have now apparently made TWO posts for the same non-post-requiring problem. Please don’t do that.

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

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:

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

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

1 Like