C# -- Populate dictionary automatically (not manually, yuck)

The title is vague cause I’m not 100% I’m doing this in a decent way. So I’m creating modular ability system in my game where the player can swap out any of their 4 skills/abilities from a list of … a lot. Here’s roughly what we’re doing:

// One of many small classes in ability file

class SpecificAbility : IAbility{
    
    // ability stuff like an Execute() method for starting specific ability functions.
}    

// Different file

class FooStuff {
    
    public Dictionary<string, IAbility> AbilityDict = new Dictionary<string, IAbility>();
}

    void UpdateAbilityDict(){
    
        AbilityDict.Add("SpecificAbility", new SpecificAbility());
    }

So, this works, and then we can easily toss abilities around allowing for the player to modify what they’re using. Cool, great. However, we currently have 16 abilities, and are planning for up to 80. Now, I do NOT want to type AbilityDict.Add() 80 times, and I’m sure I don’t need to explain why this is just bad practice. I come from Python, so dynamically loading each ability into this dictionary is childsplay where I come from. C#? I’ve got no idea, lol. I’m not even sure what the tactic is even called to do this so google as been less than helpful. Halp! Thanks guys. :slight_smile:

Are you adding to this dictionary during game play, or are you setting it up once at the start, then just reading from it for the rest of the game?

Just to be safe, I'd say both. I'd like to allow for in game updating if needed. Mainly it's a one time load though at the beginning.

would the dictionary string entry always be the name of the class?

As of now I'm still debating that part. It could be the user facing string, or just used internally. It was initially class name because I was attempting to use reflection, but turns out I don't understand it all that well and am unsure of its limitations and performance costs. For the sake of this answer let's just say it'll always be the class name. Thanks.

@Landern The issue with that is I'm still manually updating the list/xml/json etc. What I'm looking for, if it exists, is a way to pick up all the classes in a file or within a namespace, then populate the dictionary with that. There's likely going to be a lot of iterations on these abilities, so needing to manually update at every change is totally not worth it. EDIT: Re-reading your comment I'm understanding what you're saying. You're talking about what to do with the dictionary once it's populated with data. I'm talking about actually populating with the data to begin with.

2 Answers

2

Your answer is Reflection :wink:

This is one of the cases where it’s ok to use it since there’s no other way around that. If you’re happy with using the classname as dictionary key that’s quite easy. If you want to specify a seperate name you would have to add a custom Attribute to your class to give it a custom name.

Those two helper methods will give you either a list of all types in your current AppDomain or all classes which are assignable to a specified type which could be a base class or an interface.

public static class ClassUtils
{
    public static IEnumerable<System.Type> AllTypes()
    {
        var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
        foreach(var assembly in assemblies)
        {
            var types = assembly.GetTypes();
            foreach(var type in types)
            {
                yield return type;
            }
        }
    }
    public static IEnumerable<System.Type> AllTypesDerivedFrom(System.Type aBaseType)
    {
        foreach(var T in AllTypes())
        {
            if(aBaseType.IsAssignableFrom(T) && T != aBaseType)
                yield return T;
        }
    }
    public static T GetFirstAttribute<T>(this System.Type aType) where T : System.Attribute
    {
        var attributes = aType.GetCustomAttributes(typeof(T),false);
        if(attributes.Length == 0)
            return null;
        return (T)attributes[0];
    }
}

Now you just need to define a custom attribute like this:

public class CustomAbilityName : System.Attribute
{
    public string customName;
    public CustomAbilityName(string aCustomName)
    {
        customName = aCustomName;
    }
}

And this is how one of your child classes could look like:

[CustomAbilityName("Fireball")]
class SpecificAbility : IAbility{
    // ...
} 

Your initialization of your dict would look like:

var classes = ClassUtils.AllTypesDerivedFrom(typeof(IAbility));
foreach(var T in classes)
{
    IAbility inst = (IAbility)System.Activator.CreateInstance(T);
    string name = T.Name;
    var att = T.GetFirstAttribute<CustomAbilityName>();
    if (att != null)
        name = att.customName;
    AbilityDict.Add(name, inst);
}

Note: using that attribute is pure optional. If no attribute specified it would use the classname.

if inst is just an instance of the class, then having user facing names wouldn't be hard at all. I could simply add a .Name member to the base class and then have: AbilityDict.Add(inst.name, inst); Thanks for this answer. I am unfamiliar with most of it, but I believe this is what I am looking for. Would you say my method of adding the custom name will work? Also, I realized after posting this that it would be better for me to store references to the class so that I can create new instances as needed. Is this possible at all, and if so, is it possible using the logic you've provided?

Just added the attribute stuff as well since i'm not at home this weekend ;) Sure, you can use a list / dict of System.Type objects as well and use the Activator to create an instance when you need it. But creating them at start probably won't hurt. ps: In AllTypesDerivedFrom there was an important check missing T != aBaseType otherwise it would return the base class / interface as well and you probably can't create an instance of that ;)

Could I have the userFacingName member be static and access it via the Type, so I can still use a member to set the name and save the Type into the dict instead of the name?

This is absolutely the answer I wish I could have written. Thank goodness there are people who are good at reflection ;)

Your answer here is XML serilization.

What you can do (once you understand how XML serialization works) is create your XML file that lists all your abilities and all the properties pertaining to them. Modify your ability class to have abilities include a ID (which can just come from the class name if need be, but I’m assuming in some cases you can have the same class serve the purpose of a fireball and an icebolt but the dmg type property will be different along with other properties).

class SpecificAbility : IAbility
{
  [XMLElement("AbilityID")]
  public string ID;
// ability stuff like an Execute() method for starting specific ability functions.
} 

Then read in (deserialize in this case)the XML as a container like the following:

public class AbilityContainer
    {
        [XMLElement("Ability")]
        List<IAbility> Abilities = new List<IAbility>();
    }

Then you can just iterate through the list of abilities and add them to a dictionary with the ID as their key.

Also, I saw your comment about lots of iteration and this will work better for what you need (if I understood correctly) because your iterations will consist of modifying an XML file to, for example, change the damage amount on an ability. Then (if you read the XML file in during runtime) reloading the xml/restarting the game instead of having to rebuild/recompile, which results in faster iteration in my experience.

I just want to say that this is solid and I dig it. In my case, however, the abilities themselves don't contain many members. It's mostly logic, so XML won't save me a lot of time. It would basically just create an unnecessary layer of abstraction. Every ability will be pretty different, and the only shared member is the player invoking it. +1 though for the response. I'll certainly be checking back in on this answer for some of my other needs (which are similar). Thanks!