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?

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;