# Ideal way to instantiate abilities in a class give a dynamic list of abilities to use?

I have a PlayerClass class that is used to set my Player's class. For instance, this will make him a warrior:

 PlayerClass warrior = new WarriorClass();


WarriorClass will instantiate abilities like so:

 Ability ability1 = new LeapAbility();


Now my problem is that I will eventually dynamically update my Warrior's abilities (think talent trees or perks).

So say I give warrior a list of abilities to use. How do I do this in code? Right now I need to know the Abilities before hand and hard code their instantiation in.

Put another way, how do I instantiate a dynamic list of objects? I'm open to other solutions too if this doesn't make sense or is impossible.

• You want to decorate your warrior with a list of abilities. So **PlayerClass.AddAbility(new LeapAbility()) I guess. – Clemens Tolboom May 15 '20 at 19:21
• OK, I didn't think of feeding in an object like that. What would the other end look like? Something like this? Ability ability1 = new abilityParameter()? I'm not sure how to set it up so that the code knows to chose LeapAbility in the first place though. Only option i see is a list of all the skills in a big case or if statement. – Thisisstackoverflow May 15 '20 at 19:24
• What language you target? And you could look for design patterns like composition, decorator, abstract factory (producing players and abilities) – Clemens Tolboom May 16 '20 at 12:14

You could have a function that takes in a string, which can be loaded dynamically, and returns a new ability.

Ability createAbilityById(String s) {
switch (s) {
case “leap”: return new LeapAbility();
case “foo”: return new FooAbility();
...
}
}


You can also look into reflection if your language supports it, but it may be overkill or too complicated.

• Thanks. In concept this is where I was landing. Any idea if I've architected myself into a corner on this one? I'm not against this, it just feels big and clunky. – Thisisstackoverflow May 15 '20 at 22:43
• Well, I don't know your game, or how it's structured, but here's what I think. This is obviously clunky, and error prone, but should be okay for a solo developer. You have to think about how you define these skill trees. Are you loading them from a JSON file or something, or defining them in code? If it's the former, you would probably need a massive switch statement anyways, because it's hard to write a nice way to turn {"abilityName": "leap"} into a useful object without one. If it's the latter, just keep the skill tree code next to the creation code so you remember to update it every time. – user5074736 May 16 '20 at 1:03
• Yeah, just a solo dev working on a terraria mod. I was hoping to gain insight into how this would be done in a real game. JSON/Dictionary files came to mind but I'll get there if I need to. – Thisisstackoverflow May 16 '20 at 1:36