- Home /
GetComponent generic type
While helping a friend today, I came across a problem in Unity. The GetComponent method is generic, and needs a Type, until so far, nothing wrong.
I am using a Finite State Machine (FSM) match states to certain entities. For that case, I use generics. Every Entity, inherits from StateMachine, for this cause.
Now, when I loop through all entities in the scene, I want to get their Entity script and get a variable from it, in this case: IsKillable.
But, when Unity asks for a type, I want to give it the type: "Entity", but not "Entity" or "Minion" because I need to duplicate the functionality for every type I have.
Trying to solve that, I removed the inheritance from Entity to StateMachine, so I could easily do GetComponent(). But, how do I get that StateMachine back to work then?
I added a variable to my Entity class, with the type "StateMachine". But, in this simple case, I can't fill it with something of the type StateMachine".
To fix that, I thought about something that I once read about: covariance. With covariance, I could fill a StateMachine with a StateMachine, I atleast thought I could.
You can't use covariance on a class, so I created an interface for it, which looks like this:
public interface IStateMachine<out T>
{
}
And in my Entity class, I have a variable declared:
public IStateMachine<Entity> StateMachine;
But, now I need IStateMachine to do his work as an interface, and force the class StateMachine to have a SwitchState method, this is my current situation.
I'm trying to give my IStateMachine the method:
void SwitchState(State<T> state);
But then I get the error:
IStateMachine.cs(4,18): error CS1961: The covariant type parameter `T' must be invariantly valid on `IStateMachine<T>.SwitchState(State<T>)'
And this is where I get lost. Any help would be appreciated, from solving the error to a way different solution.
Thanks.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Are generic constraints supported? 0 Answers
C# Generic Type Inheritance 2 Answers