So I’m trying to create a weapon system by using classes and inheriting different scripts from a base one. The problem is that I don’t really know how this works (as I’m learning OOP on the way) and I got an error I don’t really know how to solve.
NullReferenceException: Object reference not set to an instance of an object
Weapon.UseWeapon () (at Assets/Weapon.cs:17)
Shooting.Update () (at Assets/Shooting.cs:23)
I have a BasicGun class where I asign its ammo, ammo used on shot, bullet type and bullet force, but when I try to shoot it throws that error. I noticed that the bullet prefab isn’t instantiating because it is null, but trying to get the prefab still doesn’t work.
Here’s the code:
public class Weapon : MonoBehaviour
{
protected Shooting player; // class Shooting is from another script, I may change this later so it makes sense
public int ammo;
public int ammoRate;
public GameObject bulletType;
public float bulletForce;
public Weapon() { }
public void UseWeapon() {
GameObject bullet = Instantiate(bulletType, player.firePoint.position, player.firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(player.firePoint.up * bulletForce, ForceMode2D.Impulse);
ammo -= ammoRate;
}
}
public class BasicGun : Weapon
{
private void Awake()
{
bulletType = GetComponent<GameObject>();
}
public BasicGun()
{
ammo = 5;
ammoRate = 1;
bulletForce = 45f;
}
}
I’m guessing from your description it is the Instantiate line which is failing (whatever line 17 is). Where exactly are you assigning the reference to “player”?
But how you troubleshoot null reference errors is always the same:
Go to the line the error refers to
Find all references used on that line
If more than 1 reference used, then before that line check each reference whether it is null
Now that you know which specific reference is null, now go figure out why you’re not assigning a reference to it before trying to use it.
As Praetor points out above, the answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!
Some notes on how to fix a NullReferenceException error in Unity3D
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.
This is the kind of mindset and thinking process you need to bring to this problem: