Alright guys I know this is a very popular question but I have no experience with managing weapon systems. I’ve seen posts suggesting creating classes (which I’ve never done but doesn’t seem too hard) and I’ve seen ways implementing an equippedWeapon variable. I don’t plan on having too many weapons in this game atm, since it’s more for me to practice my coding.
I’m using C# and am asking to be pointed in the right direction on how to go about creating a weapon manager system because repeating code and creating more variables that do pretty much the same thing just seems like bad coding!
Any tips? Thanks in advance!
using UnityEngine;
using System.Collections.Generic; //added .Generic for private List<GameObject>
public class PlayerWeapons : MonoBehaviour {
public List<GameObject> weaponList = new List<GameObject>();
public GameObject pencilWeapon;
public GameObject pistolWeapon;
private bool pencilOnOff = false;
private bool pistolOnOff = false;
//private float equippedWeapon;
void Start(){
weaponList = new List<GameObject> ();
//pencilWeapon = GameObject.FindWithTag ("PencilWeapon");
pencilWeapon.SetActive (false);
pistolWeapon.SetActive (false);
}
// Update is called once per frame
void Update () {
DrawHolsterWeapon ();
}
void OnTriggerEnter (Collider other){
//Player runs over pencil pickup, pencil is set to active
if (other.gameObject.tag == "PencilPickup") {
pencilWeapon.SetActive(true);
pencilOnOff = true;
//when pencil is active, it is addded to the weaponlist
if(pencilWeapon.activeSelf){
weaponList.Add (pencilWeapon);
Debug.Log ("You picked up a sharp ass pencil!");
Debug.Log ("Number of weapons in WeaponList: " + weaponList.Count);
}
}
//Player runs over pistol pickup, pencil is set to active
if (other.gameObject.tag == "PistolPickup") {
pistolWeapon.SetActive(true);
pistolOnOff = true;
//when pistol is active, it is addded to the weaponlist
if(pistolWeapon.activeSelf){
weaponList.Add (pistolWeapon);
Debug.Log ("You picked up a bad ass pistol!");
Debug.Log ("Number of weapons in WeaponList: " + weaponList.Count);
}
}
}
void DrawHolsterWeapon(){ //change inputs to detect and allow use for other weapons using currentEquippedWeapon
//If Q is pressed, pencil is active and pencilWeapon is in the weapon list...
if (Input.GetKeyDown(KeyCode.Q) && weaponList.Contains (pencilWeapon)) {
//holsters weapon
if(pencilOnOff == true){
pencilWeapon.SetActive(false);
pencilOnOff = false;
}
//unholsters weapon
else if (pencilOnOff == false){
pencilWeapon.SetActive (true);
pencilOnOff = true;
}
}
if (Input.GetKeyDown(KeyCode.Q) && weaponList.Contains (pistolWeapon)) {
//holsters weapon
if(pistolOnOff == true){
pistolWeapon.SetActive(false);
pistolOnOff = false;
}
//unholsters weapon
else if (pistolOnOff == false){
pistolWeapon.SetActive (true);
pistolOnOff = true;
}
}
}
}