- Home /
Is there a type which can refer to both GameObject and MonoBehaviour?
Or a way to trick one into existence?
I have this function (consider {} to be > and <):
public static void ProjectPicker{T}( ref T cur, Validator{T} validate ) where T : Component {
It builds a graphical interface to pick an object of type T from objects in the project (since Unity's ObjectField doesn't do any filtering at all).
I use the objects' parenting to sort them into folders, and as far as I know transform.parent is the only way to get the parent (right?). SO I need .transform, which both Component and MonoBehaviour have, but their parent (Object) does not.
Is there a way to write a single function that can accept both Component and MB as its T type and still access their .transform, or is there something I can do to write an override function of the other type and somehow call the original function (I'll do literally anything to not duplicate the function, including simply not support GameObjects at all), or is there another way to read an object's folder structure?
I'd like a single function, but if there's one like this I'd be fine:
public static void ProjectPicker( ref GameObject cur, Validator{GameObject} validate ) {
Component temp = ???;
ProjectPicker( ref temp, validate );
cur = (GameObject?)temp;
}
But I can't even get to .transform! This function searches prefabs for things matching the conditions in the validate function. I want to be able to say "Only search Projectile prefabs" or "Search all prefabs", and from what I can tell I would need to pass either Projectile or GameObject as the type T. Their common ancestor, Object, does not have a .transform member, so I have to find some way to convert from one to the other.
If i use where T : UnityEngine.Object, I can convert to GameObject, but I can't figure out how to convert to a Component descendent so I can send t through the validate function:
T t;
GameObject go, currentObject;
...
go = currentObject as GameObject;
if ( typeof(T) == typeof(GameObject) ) t = go as T;
else t = go.GetComponent{T}(); // "T must descend from Component"
if ( validate(t) ) { AddToPicker(); }
I need to get a component of type T, but T needs to be ensured to be a descendent of Component. I need an intermediary type:
Type x = typeof(T) as Component; // but this doesn't compile
t = go.GetComponent{x}();
Answer by Loius · Feb 19, 2013 at 07:26 PM
Transform is a Component, and every GameObject is guaranteed to have a Transform, so you can use Transform as your T type when you need to find every GameObject.
Derp.