- Home /
Is it possible to use a variable as a Type?
For instance:
Type myType = new Type //initialize somehow? I can't initialize System.Type as it is an abstract
//make changes to myType
myGameObject.GetComponent < myType >();
If this is possible, could you also then please demonstrate how to pass this to a function?
Many thanks
I'd like to create a function that will look for a myType Type of Component in a GameObject (where myType is a variable). This is just to make things more modular, I'm curious if this is possible.
Otherwise I know how to pass a specific type to GetComponent.
Answer by wildex999 · Mar 12, 2014 at 10:36 PM
You looking for something like this?
public Component getCustomComponent(string comp)
{
Type myType = Type.GetType(comp);
return myGameObject.GetComponent(myType);
}
getCustomComponent("MyCustomComponent");
Yes!
I think the crucial bit which I got errors on was the declaration you've used for myType, specifically using
Type myType = Type.GetType(comp)
ins$$anonymous$$d of using
Type myType = new Type
as System.Type is an abstract
$$anonymous$$any thanks!
Be aware tho that Type.GetType can return null if it can't find the type, checking for this is a good idea ;)
can anyone explain to me why this doesn't work anymore? i'm on unity 2020.3 and trying to do basically the exact same thing lol
Could you explain a little bit? Where's the problem? Does the compiler throw an error?