- Home /
GetComponent and converting string to Type type
Hello, quick question!
I'm trying to access scripts through GetComponent without naming the scripts explicitly.
I store the script name in
string scriptName;
and then try to access that script using
GameObject.GetComponent<scriptName>();
...however this throws the error
`MyClass.scriptName' is a `field' but a `type' was expected
Is there a way to convert my string to Unity's Type type so that GetComponent may take it?
Answer by whydoidoit · Jul 19, 2012 at 10:39 AM
You can use the string version of get component:
GameObject.GetComponent(scriptName);
That will return the script but it will be a type of Component that you would probably need to cast to something to make it usable. Are you using a base class or an interface to interact with it? If so:
var myObject = GameObject.GetComponent(scriptName) as BaseClassOrInterface;
$$anonymous$$mm... I've set up the scene so that the name of the base class and the name of the script I want to receive are the same. That way I can use scriptName to identify both the base class and the script.
So if I were to use the string version of GetComponent, it would solve the problem of turning scriptName into a type for GetComponent to use, but then I would need to find a way to turn scriptName into the base class reference.
I'm trying to use the string in scriptName to identify both the base class and the name of the script I'm using.
But how can your code function if it's generic and it doesn't know what the type is?
As in what are you doing with the instance of the script directly after the GetComponent() call? You can't know what methods or fields would exist, unless they are common to all of the scripts (in which case they should be in a known base class).