- Home /
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:
Why is this happening/what is going on?
If you log weapon on the line before the instantiate does it come back null?
Yes. When logged before the assignment in UpdateWeapon(), it comes back null, when logged after it comes back properly, then when logged before Instantiate it's null again.
Answer by Vega4Life · Aug 02, 2019 at 05:39 PM
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.