Search Unity

Optimizing Scripts with many if Statements (C#)

Discussion in 'Scripting' started by dann96, May 27, 2015.

  1. dann96

    dann96

    Joined:
    Dec 6, 2014
    Posts:
    113
    I'm hoping that this isn't too much to ask, but I'm looking into optimizing a script I've made that takes in and organizes a collection weapons that the player picks up. While it performs the way I want it to, I've begun to realize that the script is reaching over 200 lines just by coding three weapons. Is there any way to simplify this?
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class WeaponSelection : MonoBehaviour
    6. {
    7.     //WeaponHolders
    8.     private GameObject PistolHolder;
    9.     private GameObject ARHolder;
    10.     private GameObject ShotgunHolder;
    11.  
    12.     private GameObject Weapon;
    13.     //Gameobject texts that count each ammo types
    14.     private GameObject PistolAmmoCountObject;
    15.     private Text PistolAmmoText;
    16.     private GameObject ShotgunAmmoCountObject;
    17.     private Text ShotgunAmmoText;
    18.     //gun components that count for booleans (null or existing)
    19.     private Gun_Pistol PistolRegistry;
    20.     private Gun_AR ARRegistry;
    21.     private Gun_Shotgun ShotgunRegistry;
    22.     //Keys for each Holdertype
    23.     private KeyCode PistolKey;
    24.     private KeyCode ARKey;
    25.     private KeyCode ShotgunKey;
    26.     //Does the registry have a gun in it? (Used to turn keycodes on and off)
    27.     private bool hasPistol;
    28.     private bool hasAR;
    29.     private bool hasShotgun;
    30.     //counters for each ammo type
    31.     public float PistolAmmoCount = 10;
    32.     public float ShotgunAmmoCount = 10;
    33.  
    34.     void Start()
    35.     {
    36.         PistolHolder = GameObject.Find ("PistolHolder");
    37.         PistolAmmoCountObject = GameObject.Find ("PistolAmmoCount");
    38.         PistolAmmoText = PistolAmmoCountObject.GetComponent<Text> ();
    39.         hasPistol = false;
    40.        
    41.         ShotgunHolder = GameObject.Find("ShotgunHolder");
    42.         ShotgunAmmoCountObject = GameObject.Find("ShotgunAmmoCount");
    43.         ShotgunAmmoText = ShotgunAmmoCountObject.GetComponent<Text> ();
    44.         hasShotgun = false;
    45.  
    46.         ARHolder = GameObject.Find ("ARHolder");
    47.         hasAR = false;
    48.     }
    49.  
    50.     void Update()
    51.     {
    52.         if (hasPistol == true)
    53.         {
    54.             PistolRegistry = PistolHolder.GetComponentInChildren<Gun_Pistol>();
    55.             PistolKey = KeyCode.Alpha1;
    56.         }
    57.         if (hasAR == true)
    58.         {
    59.             ARRegistry = ARHolder.GetComponentInChildren<Gun_AR>();
    60.             ARKey = KeyCode.Alpha2;
    61.         }
    62.         if (hasShotgun == true)
    63.         {
    64.             ShotgunRegistry = ShotgunHolder.GetComponentInChildren<Gun_Shotgun>();
    65.             ShotgunKey = KeyCode.Alpha4;
    66.         }
    67. /////////
    68.         //Pistol
    69.         if (Input.GetKey (PistolKey) && PistolAmmoCount >= 0)
    70.         {
    71.             PistolHolder.SetActive (true);
    72.             //If the other holders have weapons in them as well, Turn them off
    73.             if (hasAR == true)
    74.             {
    75.                 ARHolder.SetActive (false);
    76.             }
    77.             if(hasShotgun == true)
    78.             {
    79.                 ShotgunHolder.SetActive(false);
    80.             }
    81.         }
    82.         else if (PistolAmmoCount <= 0)
    83.         {
    84.             PistolHolder.SetActive (false);
    85.         }
    86.         //Assault Rifle
    87.         if (Input.GetKey(ARKey))
    88.         {
    89.             ARHolder.SetActive (true);
    90.             if(hasPistol == true)
    91.             {
    92.                 PistolHolder.SetActive(false);
    93.             }
    94.         }
    95.         //Shotgun
    96.         if (Input.GetKey (ShotgunKey) && ShotgunAmmoCount >= 0)
    97.         {
    98.             ShotgunHolder.SetActive (true);
    99.             if(hasPistol == true)
    100.             {
    101.                 PistolHolder.SetActive(false);
    102.             }
    103.             if (hasAR == true)
    104.             {
    105.                 ARHolder.SetActive (false);
    106.             }
    107.         }
    108.         else if (ShotgunAmmoCount <= 0)
    109.         {
    110.             ShotgunHolder.SetActive (false);
    111.         }
    112. //////////////////
    113.     }
    114.  
    115.     void OnGUI()
    116.     {
    117.         PistolAmmoText.text = "Count: " + PistolAmmoCount.ToString ();
    118.     }
    119.  
    120.     void OnTriggerEnter(Collider collider)
    121.     {
    122.  
    123.         if (collider.gameObject.CompareTag ("PickupPistol"))
    124.         {
    125.             Debug.Log("Pickup Type: Pistol");
    126.             Weapon = Resources.Load("weapons/pistol") as GameObject;
    127.  
    128.             if(PistolRegistry == null)
    129.             {
    130.                 Debug.Log("No Pistol found. adding instance");
    131.                 GameObject PistolInstance = Instantiate(Weapon, PistolHolder.transform.position, PistolHolder.transform.rotation) as GameObject;
    132.                 PistolInstance.transform.parent = PistolHolder.transform;
    133.                 hasPistol = true;
    134.                 Input.GetKey(PistolKey);
    135.             }
    136.  
    137.             else if(PistolRegistry != null)
    138.             {
    139.                 Debug.Log("PistolHolder already contains weapon");
    140.             }
    141.  
    142.             Destroy (collider.gameObject);
    143.         }
    144.  
    145.         if (collider.gameObject.CompareTag("PickupAR"))
    146.         {
    147.             Debug.Log("Pickup Type: AR");
    148.             Weapon = Resources.Load("weapons/AR") as GameObject;
    149.            
    150.             if(ARRegistry == null)
    151.             {
    152.                 Debug.Log("No AR found. adding instance");
    153.                 GameObject ARInstance = Instantiate(Weapon, PistolHolder.transform.position, PistolHolder.transform.rotation) as GameObject;
    154.                 ARInstance.transform.parent = PistolHolder.transform;
    155.                 hasAR = true;
    156.                 Input.GetKey(ARKey);
    157.             }
    158.            
    159.             else if(ARRegistry != null)
    160.             {
    161.                 Debug.Log("ARHolder already contains weapon");
    162.             }
    163.         }
    164.         if (collider.gameObject.CompareTag ("PickupShotgun"))
    165.         {
    166.             Debug.Log("Pickup Type: Shotgun");
    167.             Weapon = Resources.Load("weapons/Shotgun") as GameObject;
    168.            
    169.             if(ShotgunRegistry == null)
    170.             {
    171.                 Debug.Log("No Shotgun found. adding instance");
    172.                 GameObject ShotgunInstance = Instantiate(Weapon, ShotgunHolder.transform.position, ShotgunHolder.transform.rotation) as GameObject;
    173.                 ShotgunInstance.transform.parent = ShotgunHolder.transform;
    174.                 hasShotgun = true;
    175.                 Input.GetKey(ShotgunKey);
    176.             }
    177.            
    178.             else if(ShotgunRegistry != null)
    179.             {
    180.                 Debug.Log("ShotgunHolder already contains weapon");
    181.             }
    182.            
    183.             Destroy (collider.gameObject);
    184.         }
    185.         if (collider.gameObject.CompareTag ("PickupAmmo"))
    186.         {
    187.             PistolAmmoCount  = PistolAmmoCount + 10;
    188.         }
    189.     }
    190. }
     
  2. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    You could use something with lists. Having a lists that have a gameobject, string for a tag, ect. Or make a custom class to, which has each of those variables, set it to be serialize, and use a list of that class to specify the values
     
  3. KyleStank

    KyleStank

    Joined:
    Feb 9, 2014
    Posts:
    204
    If you want a collection of weapons, make a script like "WeaponDatabase". Then inside, you could do:

    Code (csharp):
    1. using System.Collections.Generic;
    2.  
    3. public class WeaponDatabase : MonoBehaviour
    4. {
    5.     public List<Gun_Pistol> pistols = new List<Gun_Pistol>();
    6.     public List<Gun_AR> assualtRifles = new List<Gun_AR>();
    7.     public List<Gun_Shotgun> shotguns = new List<Gun_Shotgun>();
    8. }
    Then to add something to the lists, do this:
    Code (csharp):
    1. void Start()
    2. {
    3.     pistols.Add(new Gun_Pistol(param1, param2, param3));
    4. }
    And the last bit. To access something from the list, do it like a regular array:
    Code (csharp):
    1. void Update()
    2. {
    3.     print(pistols[0].name/**or any other property in the Gun_Pistol class*/);
    4.     print(pistols.Count); //Print how many items are in the 'pistols' variable
    5. }
    EDIT:
    I just realized that you are using Input.GetKeyDown(). Do not use this, use Input.GetButtonDown() instead. This lets you easily create inputs that the user can change. And you can VERY easily add controller support, as long as you set up the right buttons that map to a Xbox 360 Controller.
     
  4. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    All of your gun classes could inherit from a base class "gun".. then they could all fit in a single list<gun>... cycle through that list and grab info from the selected gun to decide what it is and where it should be mounted
     
    BenZed, erebel55, NomadKing and 2 others like this.