- Home /
How to GetComponent from Class that uses Generics
Hi, i'm tweaking a State Machine Class that allows to work with Generics to simplify work. I'm getting an error that i can't decode:
Assets/Scripts/Entities/Character.cs(60,33): error CS0309: The type `StateMachine<Character>' must be convertible to `UnityEngine.Component' in order to use it as parameter `T' in the generic type or method `UnityEngine.Component.GetComponent<T>()'
Here's the code i'm using:
_stateMachine = GetComponent<StateMachine<Character>>();
And The State Machine Class format:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class StateMachine<T> where T : MonoBehaviour {
private List<State<T>> _states = new List<State<T>>();
public void onState()
{
}
public void setState(int state)
{
}
/// <summary>
/// Adds the state.
/// </summary>
/// <param name='s'>
/// a state component.
/// </param>
public void addState(State<T> s)
{
}
}
Character Class extends MonoBehaviour, so i don't understand what it's the nature of the problem.
Any ideas??
Thanks in advance.
Francisco.
Answer by Loius · May 02, 2013 at 05:20 AM
Well it says right there, Statemachine must be convertible to Component. Statemachine must itself be a component. (MonoB is a child of Component).
If it's possible to do it'll look like this:
public class StateMachine : MonoBehaviour where T : MonoBehaviour
You might have more luck with StateMachine as a parent class/interface rather than a generic.
Your answer
Follow this Question
Related Questions
How should I use the Generic versions of GetComponent
HasComponent 4 Answers
GetComponent and AddComponent with variables for Collider type 2 Answers
Implicit type GetComponent call 0 Answers
Getting variables by their names? 3 Answers