Answer the question
In order to leave comments, you need to log in
How to get element by type in Dictionary?
I wrote a class that will store the components. Components will be implemented from different classes. The studio says that you cannot use T by key in GetComponent. What would be the right way to implement it. Maybe there is a method in the Dictionary that allows me to solve my problem?
public class DictComponent
{
public Dictionary<Type, Component> Components { get; private set; }
public DictComponent()
{
Components = new Dictionary<Type, Component>();
}
public T GetComponent<T>()
{
// НЕ РАБОТАЕТ
return (T)Components[T.GetType()];
}
public void Add(Component comp)
{
Components[comp.GetType()] = comp;
}
}
Answer the question
In order to leave comments, you need to log in
public Component GetComponent<T>()
{
// РАБОТАЕТ
return Components[typeof(T)];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question