You have to use the System.Type version and not the generic version of GetComponent.
GetComponent(Type.GetType(myString))
Note that GetComponent returns a reference of type “Component”. If you need to access specific members of a specific class you have to cast the type into the right type.
Generic parameters are not “variables” and can’t be dynamic. Compiled code uses static typing.
edit
From your comments below it seems you might want to use class inheritance. For this you don’t need to know the actual type or type name at all. If you use GetComponent with your base class type it will return whatever component is derived from that base class.
For example GetComponent<Renderer>()
will return any component that is derived from “Renderer”. So the returned class could be a MeshRenderer, SkinnedMeshRenderer, LineRenderer, SpriteRenderer, … depending on what component is actually attached to the gameobject. Of course the type of the returned reference is just Renderer so you can’t access specific members of the actual type without casting the reference into the actual type.
Instead of a base class you can also use interfaces which is usually better. GetComponent will return any component reference that does implement the given interface. The big advantage when using interfaces is that a class can implement multiple interfaces.
public interface IObjectMovement
{
void Move(Vector3 aDisplacement);
}
public class ConcreteMovement : MonoBehaviour, IObjectMovement
{
public void Move(Vector3 aDisplacement)
{
Debug.Log("Move: " + aDisplacement);
}
}
public class Controller : MonoBehaviour
{
public IObjectMovement movement;
void Start()
{
movement = GetComponent<IObjectMovement>();
}
void Update()
{
movement.Move(transform.forward);
}
}
The general the point of polymorphism is abstraction. That means you can treat a more complext class in an abstract way without knowing the actual used type. The base class or interface just defines “method contracts”.
A base class example might look like this:
public class BaseClass : MonoBehaviour
{
public virtual void Move(Vector3 aDisplacement)
{
Debug.Log("BaseClass Move");
}
}
public class DerivedClass : BaseClass
{
public override void Move(Vector3 aDisplacement)
{
Debug.Log("DerivedClass Move");
base.Move(aDisplacement);
}
}
public class Controller : MonoBehaviour
{
public BaseClass movement;
void Start()
{
movement = GetComponent<BaseClass>();
}
void Update()
{
movement.Move(transform.forward);
}
}
Here when you attach a DerivedClass to the gameobject, the call to “Move” inside update will call Move of the DerivedClass.