Error "NullReferenceException"

I am new to C# programming and I was making a FPS controller from Brackeys (while adding my own code for sprinting, crouching, etc). I wanted to add Head bobbing so I copied it from GitHub.

After polishing the movement, I made a reference to the Player Movement script in the Head Bobbing script so I could change the speed of the head bobbing for sprinting and crouching using the variables present in the Player Movement script to make movement look more natural.

After writing down the code, when I try to run the game. It provided me with 999+ more errors saying that “NullReferenceException: Object reference not set to an instance of an object HeadBob.BobbingManager () (at Assets/Scripts/HeadBob.cs:69) HeadBob.Update () (at Assets/Scripts/HeadBob.cs:25).”

I searched forums and wikis on how to solve it. People were stating that this is one of the easiest errors to solve. I couldn’t understand anything they were saying, so I decided to post the question in Unity Answers.

Here is the code for the Player Movement:-

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

public class PlayerMovement : MonoBehaviour
{
    [Header("References")]
    public CharacterController controller;
    public Camera cam;
    public LayerMask groundMask;
    private Vector3 velocity;
    public Transform groundCheck;

    [Header("Walk Settings")]
    public float walkSpeed = 5f;
    public float walkFOV = 60f;
    public float standHeight = 2f;
    [HideInInspector] public bool isWalking;
    
    [Header("Run Settings")]
    public float runFOV = 100f;
    public float runSpeed = 10f;
    [HideInInspector] public bool isSprinting;
    
    [Header("Crouch Settings")]
    public float crouchSpeed = 2f;
    public float crouchHeight = 1.4f;
    public float crouchFOV = 45f;
    public float crouchSmooth = 2f;
    [HideInInspector] public bool isCrouching;

    [Header("Player Physics")]
    public float gravity = -11f;
    private float speed;
    public float FOVSmooth = 0.5f;
    private bool isGrounded;
    public float groundDistance = 0.4f;

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

    }

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        if (isGrounded == true)
        {
            if (isCrouching == true)
            {
                Crouch();
            }
            else if (isSprinting == true)
            {
                Sprint();
            }
            else
            {
                Walk();
            }
        }

        if(Input.GetKeyDown(KeyCode.C))
        {
            if(isCrouching == false)
            { 
                isCrouching = true;
            }
            else
            {
                isCrouching = false;
            }
        }

        if(Input.GetKey(KeyCode.LeftShift))
        {
            isSprinting = true;
            isWalking = false;
        }
        else
        {
            isSprinting = false;
            isWalking = true;
        }

        controller.Move(move * speed * Time.deltaTime);

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }

    void Crouch()
    {
        if(isCrouching == true)
        {
            speed = crouchSpeed;
            controller.height = Mathf.Lerp(controller.height, crouchHeight, crouchSmooth * Time.deltaTime);
            
            if (Input.GetMouseButton(1))
            {
                cam.fieldOfView = Mathf.Lerp(cam.fieldOfView, crouchFOV, FOVSmooth * Time.deltaTime);
            }
            else
            {
                cam.fieldOfView = Mathf.Lerp(cam.fieldOfView, walkFOV, FOVSmooth * Time.deltaTime);
            }
        }

    }

    void Sprint()
    {
        if(isSprinting == true)
        {
            speed = runSpeed;
            controller.height = Mathf.Lerp(controller.height, standHeight, crouchSmooth * Time.deltaTime);
            cam.fieldOfView = Mathf.Lerp(cam.fieldOfView, runFOV, FOVSmooth * Time.deltaTime);
        }
    }

    void Walk()
    {
        if(isWalking == true)
        {
            speed = walkSpeed;
            controller.height = Mathf.Lerp(controller.height, standHeight, crouchSmooth * Time.deltaTime);
            cam.fieldOfView = Mathf.Lerp(cam.fieldOfView, walkFOV, FOVSmooth * Time.deltaTime);
        }
    }
}

And here is the code for the Head Bobbing script:-

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

public class HeadBob : MonoBehaviour
{
    public PlayerMovement movementCode;

    public float walkBob = 0.05f;
    public float crouchBob = 0.01f;
    public float runBob = 0.1f;
    public float bobbingAmount = 0.2f;
    public float midpoint = 2.0f;
    
    private float timer = 0.0f;
    private float bobbingSpeed = 0.18f;

    void Start()
    {
        movementCode = GetComponent<PlayerMovement>();
    }
    void Update()
    {
        Headbob();
        BobbingManager();
    }

    
    void Headbob()
    {
        float waveslice = 0.0f;
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        if (Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0)
        {
            timer = 0.0f;
        }
        else
        {
            waveslice = Mathf.Sin(timer);
            timer = timer + bobbingSpeed;
            if (timer > Mathf.PI * 2)
            {
                timer = timer - (Mathf.PI * 2);
            }


            Vector3 v3T = transform.localPosition;
            if (waveslice != 0)
            {
                float translateChange = waveslice * bobbingAmount;
                float totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
                totalAxes = Mathf.Clamp(totalAxes, 0.0f, 1.0f);
                translateChange = totalAxes * translateChange;
                v3T.y = midpoint + translateChange;
            }
            else
            {
                v3T.y = midpoint;
            }

            transform.localPosition = v3T;
        }
    }

    void BobbingManager()
    {
        if (movementCode.isCrouching == true)
        {
            crouchBob = bobbingSpeed;
        }
        else if (movementCode.isSprinting == true)
        {
            runBob = bobbingSpeed;
        }
        else if (movementCode.isWalking == true)
        {
            walkBob = bobbingSpeed;
        }
    }
}

I would really appreciate if someone would answer me…

I suspect a NullReferenceException might have occurred because your script couldn’t find movementCode reference (under HeadBob script). You can confirm this by checking the variable under inspector once your game is running, to see if it has been assigned, since it’s being set as a public variable.

When you use GetComponent<>(), you are retrieving Components from the GameObject to which this script is attached. Therefore, ensure that both scripts are attached to the same GameObject.

You can check out this video for a more detailed explanation of the error as well as some examples, which will be beneficial for your learning.
What NullReferenceException errors are (and how to fix them)