user3014330
user3014330

Reputation: 21

Disable component even without knowing type

How do i disable components without knowing about its type? The best i got is this, but there is no enabled option on component?

Component[] tmpComponents = tmpGO.GetComponents <Component>();
foreach (Component tmpComponent in tmpComponents)
{
    if ( tmpComponent.GetType() != Transform && tmpComponent.GetType() != MeshRenderer )
    {
        tmpComponent.enabled = false; <= ???
    }
}

i also tried

tmpGO.GetComponent <tmpComponent.GetType()> ().enabled = false;

But that did not work.

Updated: I try this, but now it is giving different length.

Component[] components = tmpGO.GetComponents <Component> ();
Behaviour[] behaviours = tmpGO.GetComponents <Behaviour>();
for (int x = 0; x < components.Length; x++)
{
    if ( components[x].GetType() != typeof (Transform) && components[x].GetType() != typeof (MeshRenderer) )
    {
        Debug.Log (components.Length);
        Debug.Log (behaviours.Length);
        //behaviours [x].enabled = false;
    }
}

This does not work because asking for behaviour does not give me a full list of components that could be enabled.

Upvotes: 0

Views: 245

Answers (1)

rutter
rutter

Reputation: 11452

The compiler is trying to warn you that class Component does not have a property/field named enabled -- and it doesn't, because there are some component types that cannot be enabled/disabled.

You can, however, filter out to components with type Behaviour:

foreach (var b in tmpGO.GetComponents<Behaviour>()) {
    b.enabled = false;
}

Quoting from the manual:

Behaviours are Components that can be enabled or disabled.

Upvotes: 2

Related Questions