Help with finding a base class in a dictionary of interfaces.

I’ve become a little confused over the best way to implement a dictionary that manages the units in my game. The value in the dictionary is an interface and that works as it should right now. I haven’t used GameObject as the value as I didn’t want to be able to accidentally add units that aren’t “selectable” to my dictionary. I’d like to be able to iterate over my Dictionary and find any Objects inside that might also contain another interface or perhaps share a certain base class so that I can hand this off to my movement logic. Any Ideas?

I have a feeling that Generics might be able to help here but I can’t quite figure out how.

Below is how I’ve set up my class.

public static class SelectionManager
{
    static Dictionary<int, ISelectable> selectedUnits = new Dictionary<int, ISelectable>();

    public static void SelectUnit(ISelectable selectable)
    {
        // Add Logic
    }

    public static void DeselectUnit(int id)
    {
        // Remove Logic
    }

    public static void DeselectAllUnits()
    {
        // Clear Logic
    }
}

A quick way around this would be to have a GameObject property in your ISelectable interface:

public interface ISelectable{
[...]
GameObject GO {get;}
}

public class WhateverClass : Monobehaviour, ISelectable{
[...]
public GameObject GO{get{return gameObject;})
}

You can’t have variables on interfaces but you can have properties. Instead of a GameObject you could have one for your movement script or whatever you need however exposing the GameObject directly means you can just call GetComponent() to retrieve whatever component you need.

1 Like