- Home /
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.
Answer by BastianUrbach · Jul 21, 2020 at 12:19 PM
Generally you should prefer the generic version of GetComponent, which has the correct return type instead of just Component, e.g.:
Collider c = GetComponent<Collider>();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);
Answer by CodesCove · Jul 21, 2020 at 11:21 AM
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>();
The fact is that there are other UnitBehaviours except AttackNearset and need to set string name of specific script in ispector and get component by this string and then use its methods but Invoke is $$anonymous$$onoBehaviour method not Component and I can't use it.
ok, didn't know your specific need.. reflection works as BastianUrbach answered.. also if you need to access the variables (via member info) then use type.GetField("varname") https://docs.microsoft.com/en-us/dotnet/api/system.type.getfield?view=netcore-3.1
Your answer
Follow this Question
Related Questions
Unity can't see any scripts 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Help removing an AudioSource component from another script 0 Answers
Zenject add component dynamically 2 Answers