Enable/Disable a Component by using a String Variable for the Component name

Hi,
I need to Enable a component by string.

i am trying to this :
go.GetComponent<myComponent>.Enabled = true;
but i want to be a variable so now i am getting my component like this :

aComponent = go.GetComponent(componentNameString);

But i can’t do :

aComponent.Enable = True;

the ‘componentNameString’ is given by the user in the inspector
that’s the main reason why i need to use a string.

A Component doesn’t have an “enabled” property. Only some specific derived classes have one. For example your own scripts get their enabled property from the Behaviour class. The MonoBehaviour class is derived from Behaviour. So if the components you want to enable / disable are scripts (components derived from MonoBehaviour) or other components derived from Behaviour you can simply cast the result of GetComponent to “Behaviour”. This allows you to use it’s enabled property.

Be careful that when the actual component that is returned can’t be casted to Behaviour an exception would be thrown.

Have a look at this class hierachy(it’s old but the core classes are there). As you can see even many built-in components are derived from Behaviour. However there are some components that also have an enabled property but are not derived from Behaviour (like Renderer and all it’s child classes).

To cover most components you can do it like this:

// C#
var comp = go.GetComponent(componentNameString);
Behaviour be = comp as Behaviour;
if (be != null)
{
    be.enabled = true;
}
else
{
    Renderer rend = comp as Renderer;
    if (rend != null)
        rend.enabled = true;
}

Another way might be to use reflection to search for an actual property with the name “enabled”. However reflection can cause many problems if not used properly and is generally slow. Though it would allow to set the “enabled” property of any kind of component.

I think it should works if you get all assembiles and then get all types. If you have them all, just compare to string and you will have the one you are looking for. Then you can use GetComponent and set enable/disable.