Search Unity

Avoiding unneeded? if statements

Discussion in 'Scripting' started by flipwon, Oct 13, 2019.

  1. flipwon

    flipwon

    Joined:
    Dec 29, 2016
    Posts:
    179
    Hey guys,
    inb4 I'm too noob to understand. I'm trying to make a consumable item buff system that uses scriptable objects. My character has stat classes and within those stats contains a list of modifiers. In my scriptable object I set the int amount of the buff and create a modifier, adding it to the stat. My problem is with how many if statements I have as of now, and I'd like to add all of my stats in the future.

    A picture may help me make more sense:
    upload_2019-10-13_17-27-19.png

    The buff to add is shown in the editor, and if one (or more) are set, they are passed to the playercontrollers stats (after checking if the buff already exists in the players list, part of the addbuff method).

    So the question is how can I check through all the available buff values, and have them associated to the players Stat class so I can do a simple loop instead within an overridden method?
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Welcome. In the future, use CODE tags to share code, rather than a picture.

    If you see yourself repeating things, you can usually extract the common functionality into a method, and just pass in the values that are dynamic. For example:

    Code (CSharp):
    1. private void ApplyStatBuff(StatType statType, int buffAmount) {
    2.     if (buffAmount > 0) {
    3.         StatModifier mod = new StatModifier(buffAmount, ModType, parentItem);
    4.         AddBuff(mod, statType);
    5.     }
    6. }
    Then instead of all your Ifs, you'd just call ApplyStatByff(pc.Strength, StrengthBuff);
     
    flipwon likes this.
  3. flipwon

    flipwon

    Joined:
    Dec 29, 2016
    Posts:
    179
    Thank you, sir. I knew this was super simple and I was overthinking the whole thing. Kind of an embarrassing lesson to be reminded of. Also, I'm aware of using code blocks, I honestly couldn't tell you why I used a screen shot, I think I'm just so used to sending screen shots via discord it sorta happened :p

    Thank you again, truly!