- Home /
Question by
Xxbz · Mar 08, 2014 at 12:39 PM ·
monobehaviourcomponentsgenerics
Associate a data object to Monobehaviours with generic
Hi,
I can't figure out my problem.
I would like to add a Data object in some of my MonoBehaviours.
So, i have created an abstract class like this
public abstract class DataMonoBehaviour<T> : MonoBehaviour
where T : BaseData, new()
{
protected T Data;
protected DataMonoBehaviour()
{
Data = new T();
}
protected virtual T GetData()
{
if (Data == null)
return default(T);
return Data;
}
}
I have also a class for my Data objects :
public class BaseData { }
And some derived Data classes with properties on it :
public class DataA : BaseData { }
public class DataB : BaseData { }
So now i can create Monobehaviours associated with a Data object :
public class MonobehaviourA : DataMonoBehaviour<DataA> { }
public class MonobehaviourB : DataMonoBehaviour<DataB> { }
What i want to achieve is get all components of a GameObject that inherites from DataMonoBehaviour (no matter the type of T).
foreach (var component in gameObj.GetComponents(typeof(DataMonoBehaviour<BaseData>)))
{
}
But this doesn't work..
Then i want to convert this component back to DataMonoBehaviour
so i can do this :
((Convert back to DataMonoBehaviour<BaseData>)component).GetData();
to return my Data object associated with the DataMonoBehaviour
I don't know if it is possible to do so. If not, which are the possible solutions ???
Thanks you!
K
Comment