I have the following code:
private Dictionary<int, Entity> m_allEntities;
private Dictionary<Entity, List<IComponent>> m_entityComponents;
public Dictionary<int, T> GetComponentType<T>() where T: IComponent
{
Dictionary<int, T> components = new Dictionary<int, T>();
foreach (KeyValuePair<int, Entity> pair in m_allEntities)
{
foreach (T t in m_entityComponents[m_allEntities[pair.Key]])
{
components.Add(pair.Key, t);
}
}
return components;
}
m_allEntities = Dictionary of all Entities with Key: their ID and Value: the Entity object. m_entityComponents = Dictionary of all Entities and their component list with Key: Entity object and Value: it's list of components.
I have several different classes that implement the IComponents interface. What the GetComponentType() function is supposed to do is loop through all entities and create a dictionary of entity IDs and components of a particular type.
For example: if I want to get a list of all Entities that have a Location component then I would use:
entityManager.GetComponentType<Location>();
The problem that I'm running into is the second loop because it doesn't seem to be filtering through my Dictionary. Instead it tries to cast all components in the dictionary to the Location type which, of course, throws an exception. How can I alter this code so that it does what I want it to do?
If your collection has different types you'll need to test for the proper type.
public Dictionary<int, T> GetComponentType<T>() where T: IComponent
{
Dictionary<int, T> components = new Dictionary<int, T>();
foreach (KeyValuePair<int, Entity> pair in m_allEntities)
{
foreach (IComponent c in m_entityComponents[m_allEntities[pair.Key]])
{
if (c is T)
components.Add(pair.Key, (T)c);
}
}
return components;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With