Search Unity

Is there any way to simplify?

Discussion in 'Scripting' started by james2406, Nov 28, 2015.

  1. james2406

    james2406

    Joined:
    Nov 28, 2015
    Posts:
    2
    I'm getting into programming and want to stick to the DRY principle. Is there any way to simplify this code?

    Thank you in advance!

    Code (CSharp):
    1. int VMWhiteCount, VMBlackCount, VSWhiteCount, VSBlackCount, WSWhiteCount, WSBlackCount;
    2.  
    3. voidUpdate () {
    4. boolmouseHit = player.GetComponent<Purchase> ().mousePress;
    5. stringitem = player.GetComponent<Purchase> ().itemHit;
    6.  
    7. if (item == "VMWhite") {
    8. VMWhiteCount++;
    9. VMWhite.SetActive(true);
    10. }
    11. if (item == "VMBlack") {
    12. VMBlackCount++;
    13. VMBlack.SetActive(true);
    14. }
    15. if (item == "VSWhite") {
    16. VSWhiteCount++;
    17. VSWhite.SetActive(true);
    18. }
    19. if (item == "VSBlack") {
    20. VSBlackCount++;
    21. VSBlack.SetActive(true);
    22. }
    23. if (item == "WSWhite") {
    24. WSWhiteCount++;
    25. WSWhite.SetActive(true);
    26. }
    27. if (item == "WSBlack") {
    28. WSBlackCount++;
    29. WSBlack.SetActive(true);
    30. }
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    One solution - Dictionary<string,GameObject>
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    I typically use a pattern something like this. Its not actually simpler. But it is DRY. And its far easier to maintain in the long run. I made some assumptions about the meta program, so don't copy this verbatim.

    Code (CSharp):
    1. [System.Serialisable]
    2. public class VMObject {
    3.     public int count;
    4.     public GameObject object;
    5.     public VMColour colour;
    6. }
    7.  
    8. public enum VMColour {White, Black, Blue, Green}
    9.  
    10. public class VMManager : MonoBehaviour{
    11.  
    12.     // A dictionary would also work, but its not easily serialized
    13.     List<VMObject> vmList = new List<VMObject>();
    14.  
    15.     void Start () {
    16.         // Populate vmList. Or serialize it in the inspector
    17.     }
    18.  
    19.     void DoSomethingWithVMs (VMColour colour) {
    20.         for (int i = 0; i < vmList.Count; i++){
    21.             if (vmList[i].colour == colour){
    22.                 vmList[i].count++;
    23.                 vmList[i].object.SetActive(true);
    24.             }
    25.         }
    26.     }
    27.  
    28. }
     
    james2406 likes this.
  4. james2406

    james2406

    Joined:
    Nov 28, 2015
    Posts:
    2
    Thanks for your help!
    I've got it working :)
     
    Kiwasi likes this.