I have made a weapon and ammo system for my game. Weapons are switched by enabling/disabling them via script, and the weapons are child objects attached to the player.
Each weapon’s ammo system is scripted in the same script as the weapon mechanic, and each weapon has its own ammo.
I have created ammo pickups specific to each weapon:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PistolPickup : MonoBehaviour {
Pistol pistol;
// AK47 ak47; WIP
//ShotgunWeapon shotgun; WIP
void Awake ()
{
pistol = GameObject.Find ("Player").GetComponentInChildren<Pistol> ();
}
void Update ()
{
transform.Rotate (new Vector3 (0, 90, 0) * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Player"))
{
pistol.currentClips += 1;
Debug.Log ("Pickup");
gameObject.SetActive (false);
}
else
{
return;
}
}
}
And it works while I have pistol selected and get the pickup. The problem arises when I get the pickup with any other weapon selected (and thus, in this case, the object pistol disabled). In that situation, it gives an NullReferenceException error:
NullReferenceException: Object reference not set to an instance of an object
PistolPickup.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Managers/Pickups/PistolPickup.cs:27)
How do I get this script to add clips to the pistol while I have selected any other weapon?
I suppose one way could be moving the ammo system separate from the weapon scripts, but are there any other, more efficient ways?
And after experimenting, I feel the “return” at the end of the code is not required, since there is no more code after the OnTriggerEnter(Collider other)?