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): int VMWhiteCount, VMBlackCount, VSWhiteCount, VSBlackCount, WSWhiteCount, WSBlackCount; voidUpdate () { boolmouseHit = player.GetComponent<Purchase> ().mousePress; stringitem = player.GetComponent<Purchase> ().itemHit; if (item == "VMWhite") { VMWhiteCount++; VMWhite.SetActive(true); } if (item == "VMBlack") { VMBlackCount++; VMBlack.SetActive(true); } if (item == "VSWhite") { VSWhiteCount++; VSWhite.SetActive(true); } if (item == "VSBlack") { VSBlackCount++; VSBlack.SetActive(true); } if (item == "WSWhite") { WSWhiteCount++; WSWhite.SetActive(true); } if (item == "WSBlack") { WSBlackCount++; WSBlack.SetActive(true); }
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): [System.Serialisable] public class VMObject { public int count; public GameObject object; public VMColour colour; } public enum VMColour {White, Black, Blue, Green} public class VMManager : MonoBehaviour{ // A dictionary would also work, but its not easily serialized List<VMObject> vmList = new List<VMObject>(); void Start () { // Populate vmList. Or serialize it in the inspector } void DoSomethingWithVMs (VMColour colour) { for (int i = 0; i < vmList.Count; i++){ if (vmList[i].colour == colour){ vmList[i].count++; vmList[i].object.SetActive(true); } } } }