Thus far I have created two weapons for the Player, and over time I’ll be adding a variety of other weapons to the arsenal. To easily swap between weapons in Play mode, I introduced a weapon switching system. Improving the weapon system makes it easier to switch between or add new weapons. In today’s article I’ll be explaining how it works.
In the previous article I have added the ‘WeaponHolder’, a grandchild of the Player and the parent for all Weapons. This means that the Weapons are carried by the Player at all times. To the ‘WeaponHolder’ GameObject I attached a new ‘WeaponSwitching.cs’, allowing us to deactivate the weapons we don’t need and activate the one(s) we need, at start or on input.
To start we need an integer variable to store an ID for each weapon that is a child of the ‘WeaponHolder’. In Start(), the standard weapon (Laser Weapon) is assigned as “0”, the first hierarchical child of the parent ‘WeaponHolder’.
Then we need a method to activate the Weapon, and deactivate the ones we don’t need. We call this method once in Start() and once every time we select a weapon. For each indexed child in the parent, if the index is equal to the selected weapon ID; activate this weapon and deactivate all the others.
We also need a method to select a weapon, for this we hook up a key input to each weapon ID and activate the corresponding weapon if the ID has changed. If we want to select the second child (weapon) for example, we first check if there are two or more children present and so on for the following ones.
To get a better view in the inspector of which Weapon is currently selected, I reference the weapon GameObject that is currently active, like so;
Now we also have to make a small adjustment to the Weapon.cs. Since we only called the firing coroutine at the start, each time we’d swap weapons they would not fire. To fix that we need to start the coroutine again each time the weapon is activated. I also made sure that if a weapon is disabled ‘_isFiring’ is set to false, because firing and at the same time swapping weapons would leave it set as true.
Having improved the Weapon System, I can easily add new weapons and switch between them in Play mode. It doesn’t matter how many weapons are added, as long as the order in the Hierarchy matches their ID.
Up next we’ll have a look at how we can change between scenes in Unity.