Call compoent by name

Is there a way to find component by name and work with its methods? I tried to use this contruction

Type type = Type.GetType("UnitBehaviourAiAttackNearet");
Component script = gameObject.GetComponent(type);

but it doesn’t allow me to call any methods. or work with variables.

Generally you should prefer the generic version of GetComponent, which has the correct return type instead of just Component, e.g.:

Collider c = GetComponent&ltCollider&gt();

But assuming you have a good reason to work with strings instead: you have to use reflection to call the methods because the compiler can’t find them without knowing the type at compile time:

var type = Type.GetType("TypeName");
var component = gameObject.GetComponent(type);
var method = type.GetMethod("MethodName");
var parameters = new object[] { /* parameters */ };
var returnValue = method.Invoke(component, parameters);

You can set it like this:

UnitBehaviourAiAttackNearet script = gameObject.GetComponent(typeof(UnitBehaviourAiAttackNearet)) as UnitBehaviourAiAttackNearet;

Now you can access the public methods and variables of the script.

You can also use generic form (that is better):

 UnitBehaviourAiAttackNearet script =  gameObject.GetComponent<UnitBehaviourAiAttackNearet>();