Search Unity

Disable a List of components of unknown type

Discussion in 'Scripting' started by Rodolfo-Rubens, Aug 28, 2014.

  1. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    How do I do this? I want to disable a list of components that I will assign through the editor and I want them to be any type of component (not only MonoBehaviours, but lights, MeshRenderers and etc...), how can I do this?
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,702
    All of these types inherit from Component. Unfortunately, Component doesn't have an enabled property. Instead, each subclass, such as Render, Collider, and MonoBehaviour, define their own enabled properties. However, since they're all Components, you can define a list and disable them like this:

    Code (csharp):
    1. public class DisableComponents : MonoBehaviour {
    2.     public Component[] components;
    3.  
    4.     void Start() {
    5.         foreach (var component in components) {
    6.             DisableComponent(component);
    7.         }
    8.     }
    9.  
    10.     void DisableComponent(Component component) {
    11.         if (component is Renderer) {
    12.             (component as Renderer).enabled = false;
    13.         } else if (component is Collider) {
    14.             (component as Collider).enabled = false;
    15.         } else if (component is Behaviour) {
    16.             (component as Behaviour).enabled = false;
    17.         }
    18.     }
    19. }
     
  3. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    Hey, thanks TonyLi! I passed one hour looking for a solution, thanks!
     
  4. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,702
    Happy to help!