Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a Generic Dictionary throws Exception

Tags:

c#

.net

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?

like image 983
Kittoes0124 Avatar asked Feb 10 '26 22:02

Kittoes0124


1 Answers

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;
}
like image 81
ChaosPandion Avatar answered Feb 12 '26 15:02

ChaosPandion