Why am I getting this error message? (C#)

I am using the following code in a game I am developing (irrelevant code removed):

public class WeaponSpawner : MonoBehaviour
{
    GameObject weapon;
    
    public void UseWeapon()
    {
        Instantiate(weapon, transform.position, Quaternion.Euler(direction), transform);
    }

    public void UpdateWeapon(GameObject newWeapon)
    {
        weapon = newWeapon;
    }
}

I call the UpdateWeapon() method from the game menu when changing the active weapon, and I call the UseWeapon() method when actually attacking.

For some reason, however, even though the UpdateWeapon() works fine (confirmed with Debug.Log() and inspector while game is running) assigning the new weapon, when I attempt to call UseWeapon() afterwards, I get the following error:

“UnassignedReferenceException: The variable weapon of WeaponSpawner has not been assigned.”

Edit: Added in some Debug.Log and tried a different way of instantiating:

    public void UseWeapon()
    {
        Debug.Log(weapon);
        GameObject createdWeapon = Instantiate(weapon,transform.parent);
    }

    public void UpdateWeapon(GameObject newWeapon)
    {
        Debug.Log("Current physical weapon: " + weapon);
        Debug.Log("Switching physical weapon to: " + newWeapon);
        weapon = newWeapon;
        Debug.Log("New physical weapon: " + weapon);
    }

Here is a readout of the Log:

144111-error-message.png
Why is this happening/what is going on?

It has to be because you are calling UseWeapon before you are calling UpdateWeapon. If you do that, weapon is null. So make sure you either are doing a null check on weapon (in the UseWeapon() method), or just make sure that situation can’t happen.