Creating a Weapon Manager: GDJ 21

Brett Blandford
2 min readJun 6, 2021

The next thing new feature to my game is supposed to be a new weapon type. As I was thinking about what to do, I realized that my Player script was handling what weapon was being used. I feel handling what weapon is being used is outside of the scope of the Player script and I figured it would be easier and more organized for future me if I had a script dedicated to weapon logic.

The first thing I did was make an empty game object that is the child of the Player named “Weapon_Manager” and reset the location so it is in the same exact position as the player. Then I copied all of the weapon related methods and variables from the player on to a new script named “WeaponManager”. After attaching this script to my Weapon _Manager game object, and deleting the copied code from the Player, it worked just like it did before!

Since I now had a script just dedicated to weapons, I though of some better ways to do some stuff that I changed as well. So let’s go through the code!

The first big change is that there is an array of the weapon prefabs instead of a variable for each one. This allows me to create an int _weaponID variable that identifies the correct weapon based of their position in the _weaponPrefab array.

Above in my Shoot() method, you can see how I use the new array and _weaponID in the Instantiate call. Doing it this way prevents me from creating a Boolean variable for each new weapon type that is added and then checking which one is true with a lot of if statements. Where I would normally set the correct Boolean to true, I now change _weaponID to the correct array position.

There is a bit of a sneak peak of my Drone Shot weapon type which will be my next post, but I thought it would be useful to show how this is used with multiple weapon types. The _ammoUsed variable determines how much ammo is consumed when this type of weapon is fired. In the Coroutines, _weaponID is set back to 0, the base laser, and the _ammoUsed is set back to 1.

I think it was a great choice to make a weapon script and rework the code because it will be much easier to implement new weapon types in the future!

End of GDJ 21

--

--