Search code examples
c#arraysfunctionrepeat

How to condense repeating code in c# without using a bunch of arrays?


So I'm trying to write some code to give 4 different skills cooldowns. I know what code I have to write, but as it stands now, I'll have to repeat everything 4 times. I tried condensing it, but with the way I did it, I'd have to make arrays of everything, which will also take up a lot of space. Here's what needs to be done:

When a skill gets activated, it can't be pressed anymore. It then starts the cooldown by subtracting Time.deltaTime from a starting value (the total cooldown time). When the cooldown ends, you can press the button again.

At the moment I have made one of them work, but I don't think there is a way for me to use one function for all 4 skills without having a ton of arrays. Example:

void UseSkill()
{
  isCooldown[skillNum] = true;
  cooldownTimer[skillNum] = cooldownTime[skillNum];
  textCool[skillNum].gameObject.SetActive(true);
  activated[skillNum] = false;
  //activated is only when a skill has a duration. UseSkill() gets called after the duration
}

That bit of code would already require 5 arrays. If I get rid of the arrays, everything would overlap and it would break (for example: skill 1 will get the cooldown time of skill 2).

My question: is there a way to condense repeating code without using a bunch of arrays? If so, how?

Thanks in advance


Solution

  • As I wrote in the comment. Create a Skill class and use that in a list (or Dictionary<SkillEnums, Skill>). Here's just a simple example.

    var skills = new List<Skill>();
    
    skills.Add(new Skill { IsCoolDown = false, Activated = true, CooldownTimer = 100, TextCool = "Very cool" });
    skills.Add(new Skill { IsCoolDown = false, Activated = true, CooldownTimer = 100, TextCool = "Less cool" });
    skills.Add(new Skill { IsCoolDown = false, Activated = true, CooldownTimer = 100, TextCool = "A little cool" });
    skills.Add(new Skill { IsCoolDown = false, Activated = true, CooldownTimer = 100, TextCool = "Not cool" });
    
    public class Skill
    {
        public bool IsCoolDown { get; set; }
        public int CooldownTimer { get; set; }
        public string TextCool { get; set; }
        public bool Activated { get; set; }
    }