I'm writing a simple networking system. Entities are defined as classes derived from the base class Entity
. In order to identify entities over the network, I have a unique ID for each one, but when it comes time to spawn a new entity, I need a way to identify which entity type (and therefore which class) to create, so I also store a typeId
for each entity.
public abstract class Entity
{
uint id;
ushort typeId;
//abstract stuff
}
public class Entity_BeachBall : Entity
{
//overridden stuff
}
Say I have a list of all the derived entity classes like so:
public List<Type> entityTypes = new List<Type>
{
typeof(Entity_BeachBall)
};
Now I have a way to identify which class an entity uses; for instance, if typeId == 0
, then that means it should use the class Entity_BeachBall
. The problem is, how can I create a new instance of that class, even if it gets immediately implicitly cast back to the base class?
This is roughly what I want to do:
public static class EntityManager
{
public List<Type> entityTypes = new List<Type>
{
typeof(Entity_BeachBall)
};
public Entity GetNewEntity(ushort typeId)
{
return new entityTypes[typeId](); //something like this
}
}
Is this possible? If not, is there a better solution?