Unity: GetComponent <BaseClass <T>> - are there any workarounds for this?
If the object has a component with a base class BaseClass<T>, the call GetComponent<BaseClass<T>>()will not return this component. The general argument seems to discard it, since BaseClasswithout using generics it will correctly return the derived class as a component when called GetComponent<BaseClass>().
Does anyone know a solid workaround for this? Using a common argument in this class is somewhat important, so I would prefer not to rewrite the structure of the program class just for that.
Here is an example sketch of the classes in question.
//the base class that I'd like to be able to fetch the subclasses of using GetComponent
public abstract class BaseUIClass<T> : MonoBehaviour where T :BaseEntity {}
//EntityType1&2 are derived from BaseEntity
public class DerivedUIClass1 : BaseUIClass<EntityType1> {}
public class DerivedUIClass2 : BaseUIClass<EntityType2> {}
BaseUIClass has this method:
public virtual void Setup(T entity) {}
Which should be called shortly after adding the component to GO.
EDIT:
, , , ( , )
if(uiClassObj is typeof(DerivedUIClass1) go.GetComponent<BaseUIClass<EntityType1>>();
else if(uiClassObj is typeof(DerivedUIClass2) go.GetComponent<BaseUIClass<EntityType2>>();
//etc
, BaseUIClass<BaseEntity>, + , , DerivedUIClass1<EntityType1> DerivedUIClass2<EntityType2>, ?
, , , Unity , .
I.E., :
public class MyGenericClass<T> : MonoBehaviour {}
, T :
public class MySpecifiedClass : MyGenericClass<[specificType]> {}
, , , , . float int , , .
BaseClass
using UnityEngine;
public interface ISetup {
void CallSetup();
}
public class BaseClass<T> : MonoBehaviour, ISetup {
public T myEntity;
public void CallSetup() {
Setup(myEntity);
}
private void Setup(T entity) {
Debug.Log(entity);
//Your setup code
}
}
public class BaseClassInt : BaseClass<int> {
private void Awake() {
myEntity = 25;
}
}
public class BaseClassFloat : BaseClass<float> {
private void Awake() {
myEntity = 10.6f;
}
}
, Setup()
var componentsWithSetup = GetComponents<ISetup>();
foreach (var component in componentsWithSetup) {
component.CallSetup();
}