Im currently working on a Entity Component System (ECS) for a game im developing in C# and Monogame.
My GameObject class has a dictionary with all its components, and this method is written to retrieve them.
internal T GetComponent<T> (bool imperative = false) where T : Component
{
string name = typeof(T).Name;
if (!components.ContainsKey(name))
{
if(imperative)
{
T newComp = default(T);
AddComponent(newComp);
return newComp;
}
throw new Exception("Component not found");
}
return (T)components[name];
}
The thing is, that I want to pass this same function (inject this method, if you will) to a component in particular. This is because I want this component to be able to communicate with other components, without passing a reference to the dictionary.
I imagine this component should have something like this
public class UpdaterComponent: Component
{
internal Func<T> GetComponent; //where T : Component
//...
}
And then in the constructor I could pass the function from the GameObject to the Component.
However I have no idea how to write this. I have read about delegates, but I don’t want to create a delegate for everytype of Component there is. Is there a clean way to write this?
Thanks!