Need Help With a NullReference Exception

Ok, I am following the unity 3D tutorials from the official website, however I coding my own stuff as I go rather than just copying the code from the videos. The ideas is the following. I have a script where I hold data as ammo, bombs and so on. I have a spaceship shooting perfectly, but I want the ammo to decrease so I am using GetComponent to access the script holding the data and therefore be able to decrease it, however when I am going to test the code, I get a nullreferenceexception and I can’t figure out what it is.

using UnityEngine;
using System.Collections;

public class Shooting : MonoBehaviour 
{
	public GameObject laserPrefab;
	public Transform guns;
	private Inventory inventory;
	//private float laserSpeed = 50;

	// Use this for initialization
	void Awake() 
	{
		inventory = GetComponent<Inventory>();
	}

	void Start()
	{

	}
	
	// Update is called once per frame
	void Update () 
	{
		shoot();
	}

	void shoot()
	{
		if(Input.GetKeyDown(KeyCode.Space))
		{
			Instantiate(laserPrefab, guns.position, guns.rotation);
			inventory.ammo.bullets--; //This is the problem
			Debug.Log(inventory.ammo.bullets);
		}
	}
}

Any help will be appreciated, thank you very much for your time!

2 Answers

2

Is the Inventory script attached on the same gameobject this script is ?
If yes, show us inventory script.

And it’s actually better to have function that removes bullets on inventory itself, instead of tweaking it from others script.

inventory.RemoveBullets();

But in Inventory script create function

public void RemoveBullets(){
    ammo.bullets--;
}

Well. the Inventory script is attached to the parent game object. That is, I have a spaceship model with the Inventory attached to it. Then I created a child object inside the ship which are the gun points and I attached the shooting script to them.
I like to be a clear as possible so don’t mind me doing a little diagram.

ShipGameObject.

 Components
      -Moving_Script -->which works perfectly
      -Inventory_Script
 Child_Object_Guns
      Components
           -Shooting_Script

I will show you the inventory script anyway and I will try your suggestion in the meantime. Thank You!

using UnityEngine;
using System.Collections;

public class Inventory : MonoBehaviour 
{
	public class Ammo
	{
		public int bullets;
		public int missiles;
		public int bombs;
		public int health;

		public Ammo(int bull, int mss, int bmb, int hp)
		{
			bullets = bull;
			missiles = mss;
			bombs = bmb;
			health = hp;
		}
	}

	public Ammo ammo = new Ammo(200, 50, 10, 200);
	// Use this for initialization
	void Start () 
	{

	}
	
	// Update is called once per frame
	void Update () 
	{
	
	}
}