Depending on how you envision your weapon inventory working you might approach it in different ways. The best method for you will depend on how you’ve structured your project and the details of how you want it to work.
I’ve done up some quick examples of 2 common weapon systems in shooters. These won’t work as drop in replacements but they should help you in figuring out the best method for your game.
Unreal or Half Life style weapon system
In this weapon system you can carry one of each weapon.
I would approach it by using an Enum for the weapon types and a boolean array for inventory.
enum WeaponType {
PISTOL,
ASSAULT_RIFLE,
MACHINE_GUN,
SNIPER_RIFLE,
ROCKET_LAUNCHER
};
var weaponInventory : boolean[];
var currentWeapon : WeaponType = WeaponType.Pistol;
function Start () {
weaponInventory= new boolean[System.Enum.GetValues(WeaponType).Length];
}
function SwitchToWeapon (weapon : WeaponType) {
if (weaponInventory[weapon]) {
// animate putting currentWeapon away
currentWeapon = weapon;
// animate pulling out currentWeapon
}
}
function PickupWeapon (weapon : WeaponType) {
weaponInventory[weapon] = true;
SwitchToWeapon(weapon);
}
function DropWeapon (weapon : WeaponType) {
if (currentWeapon == weapon) {
var nextWeaponIndex : int = weapon + 1;
if (nextWeaponIndex >= System.Enum.GetValues(WeaponType).Length) {
nextWeaponIndex = 0;
}
SwitchToWeapon(nextWeaponIndex);
}
weaponInventory[weapon] = false;
}
Halo style weapon system
In this weapon system you have a set number of weapon slots (in this case 2) and you swap what gun is in the slot
enum WeaponType {
PISTOL,
ASSAULT_RIFLE,
MACHINE_GUN,
SNIPER_RIFLE,
ROCKET_LAUNCHER
};
var weaponSlots : int[] = new int[3] {
WeaponType.PISTOL,
WeaponType.ASSAULT_RIFLE
};
var currentWeaponIndex : int = 0;
function NextWeapon () {
var nextWeaponSlot : int = currentWeaponIndex + 1;
if (nextWeaponSlot >= weaponSlots.Length)
nextWeaponSlot = 0;
// animate putting away currentWeaponIndex
currentWeaponIndex = nextWeaponSlot;
// animate pulling out currentWeaponIndex
}
function PreviousWeapon () {
var nextWeaponSlot : int = currentWeaponIndex - 1;
if (nextWeaponSlot == 0)
nextWeaponSlot = weaponSlots.Length - 1;
// animate putting away currentWeaponIndex
currentWeaponIndex = nextWeaponSlot;
// animate pulling out currentWeaponIndex
}
function SwapWeapon (weapon : WeaponType) {
// animate putting away currentWeaponIndex
weaponSlots[currentWeaponIndex] = weapon;
// animate pulling out currentWeaponIndex
}
public class WeaponSwitch : MonoBehaviour {
public GameObject M4A1;
public GameObject Pistol;
// Use this for initialization
void Start () {
M4A1.SetActive(true);
Pistol.SetActive(false);
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("1"))
{
M4A1.SetActive(true);
Pistol.SetActive(false);
}
if (Input.GetKeyDown("2"))
{
M4A1.SetActive(false);
Pistol.SetActive(true);
}
}