NullReferenceException: Object reference not set to an instance of an object ERROR

Hello. I am getting this error on this script:
NullReferenceException: Object reference not set to an instance of an object
Can you guys please help?
PlayerGunScript.Start () (at Assets/Scripts/PlayerScripts/PlayerGunScript.cs:67)

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

public class PlayerGunScript : MonoBehaviour
{
    public int magAmmo = 0;
    public int reservedAmmo = 0;
    public int maxAmmo = 0;
    public Text ammoGUI;
    public bool canShoot = true;
    public float fireRate = 0;
    //================================================
    //Player Gun Selection
    public enum SelectedPrimaryWeaponENUM { M4A1, AK47, L115A3 };
    public enum PrimarySecondarySelectionENUM { Primary, Secondary };
    public SelectedPrimaryWeaponENUM PrimaryWeapon;
    public PrimarySecondarySelectionENUM PrimSecSelection;

    public class GunProperties
    {
        public float fireRate = 0;
        public int reloadSpeed = 0;
        public int magSize = 0;
        public int reservedSize = 0;
    }

    //======================================
    //Declaration for weapons
    //======================================

    //-M4A1-

    public GunProperties M4A1_PROPERTIES;

    void Start()
    {
        M4A1_PROPERTIES.fireRate = 0.1f;
        maxAmmo = 40;
        PrimaryWeapon = SelectedPrimaryWeaponENUM.M4A1;
        //================================
        //Weapon Setup
        //================================

        //-M4A1-

        //===============================

        //Default Weapon

        PrimaryWeapon = SelectedPrimaryWeaponENUM.M4A1;
        PrimSecSelection = PrimarySecondarySelectionENUM.Primary;

        //Set varibles according to PlayerGunSelection
        if (PrimSecSelection == PrimarySecondarySelectionENUM.Primary)
        {
            if(PrimaryWeapon == SelectedPrimaryWeaponENUM.M4A1)
            {
                //magAmmo = M4A1_PROPERTIES.magSize;
                //reservedAmmo = M4A1_PROPERTIES.reservedSize;
                //fireRate = M4A1_PROPERTIES.fireRate;
            }
        }
        //===============================

    }

Line 67
M4A1_PROPERTIES.fireRate = 0.1f;

If that is your null, it suggest there is no value for M4A1_PROPERTIES. Since this is a public variable, did you drag and drop something into it in the inspector?

Nope, it is not drag and drop.

Ok, I see the GunProperties class. The problem is you didn’t initialize the variable.
You’ll need to do

GunProperties M4A1_PROPERTIES = new GunProperties();

1 Like

Okay thank you so much! :slight_smile:

Wait, are you creating an empty object, or cloning a prefab?

Empty