Search code examples
entity-frameworkxnatheory

ID based NPC system


I have a bunch of different npcs. They all have different properties and different AI, so I have made a separate class for each type, and derive it from a base class Entity. I want to make it so that I can assign an ID to each type of Entity, so I can just call CreateNewEntity(int id, Vector2 position). How would I do this? I also have a feeling that I'm designing this badly. Is that true


Solution

  • There are a couple of ways you could do this. You could create an Attribute that will give the type some metadata such as ID e.g.

    public class RenderableEntity{
    }
    
    [EntityTypeAttribute(Name = "Wizard"]
    public class Wizard : RenderableEntity{
    }
    

    you could then bundle them all in a namespace or a logical container and create the type as follows pseudo:

    //Create Entity
    //Type Name
    string entityName = "Wizard";
    
    //Get the Type
    from the namespace where the type has the custom attribute applied to it. Get the type
    
    //Activator.Create(typeof(TheWizardType))
    

    The other is that you could just get the Type where the name matches the string you passed into your create method.