How to access scriptname from it being stored in a string variable

Hey there… Just can’t figure this one out… Have searched and searched, tried many different things, and am stumped with this one…
All I am trying to do is use a variable, that contains the name of the script, instead
of hardcoding the scriptname, when using GetComponent<>().

// The variable ScriptName contains the script for an object
// TheObject, has the script, 'TheObjectAnimation_Script',
// attached to it, and in that script, contains the variable
// 'TheNoOfAnimationControllers' set to 5
TheObject.TheObjectAnimation_Script.TheNoOfAnimationControllers = 5;
public string ScriptName = "TheObjectAnimation_Script";
public GameObject TheObject;
public int NoOfAnimationControllers;

// So TheObject has the script, "TheObjectAnimation_Script"
// attached to it.

// The problem is, that ScriptName is a string,
// so how would you use this?
NoOfAnimationControllers = TheObject.GetComponent<ScriptName>().TheNoOfAnimationControllers;

The problem here, is that the name of the script, is stored in a variable called ScriptName.
How would one use this with GetComponent<>, or GetComponent(), etc, etc, etc
Thanks for any help ahead of time…

One of the overload methods for GetComponent is string type. So it would just be GetComponent(string). However, if you want to pass a reference, you will need to cast it to the type.

var myObj = TheObject.GetComponent(myString) as MyClass;

//or

var myObj = (MyClass)TheObject.GetCompoent(myString);

Even if you get the component by string instead of by typename, your code still won’t compile, because not every script in the world has a field called “TheNoOfAnimationControllers” and so the compiler won’t let you access that field. (Imagine if your string had a value like “Button” or “Transform”; how would that work?)

I’m not really sure what you’re trying to accomplish here, but the typical way to create a function or class that can act on multiple data types is to use generics. In order to access a special member like “TheNoOfAnimationControllers”, you can leverage polymorphism by defining an interface or base class that includes that member and then use a constraint to limit your generic type or function to only work with that base type.