Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Get *ALL* components in a GameObject

Discussion in 'Scripting' started by pospi, Nov 4, 2009.

  1. pospi

    pospi

    Joined:
    Oct 22, 2009
    Posts:
    3
    I've been digging through the forums for this for hours, it's totally time to just ask lol:

    All the component grabbing functions unity provides require a Type parameter, which makes them useless when you want to get back every component attached to the gO.

    My reasons for doing this are to be able to get all components out of an object that are a subclass of a particular type. I can't find any snippets on doing this anywhere in particular. Here's what I have:

    Code (csharp):
    1.  
    2. public static ArrayList GetComponentsOfType<T>(GameObject o) where T : class {
    3.    
    4.     Component[] objs = o.GetComponents();  // if only, if only i could just leave this parameter list blank
    5.    
    6.     ArrayList goodObjs = new ArrayList();
    7.     T com;
    8.    
    9.     for (int i = 0; i < objs.Length; ++i) {
    10.         com = objs[i] as T;
    11.         if (com != null) {
    12.             goodObjs.Add(com);
    13.         }
    14.     }
    15.    
    16.     return goodObjs;
    17. }
    18.  
    Is there a gap in my knowledge, or am I screwed?
    Cheers
     
  2. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    I think there is a gap in your knowledge, if I understand you correctly.

    You can just do:

    Code (csharp):
    1.  
    2. GetComponents(typeof(Component));
    3.  
    To return a static array with all components on a GameObject. If you want all components that are subclasses of something, just get the parent class:

    Code (csharp):
    1.  
    2. GetComponents(typeof(Fruit));
    3.  
    Will return an array that includes all of your Apple, Orange, Pear, etc components.

    P.S. I think that typeof() syntax is correct for C# (we use JS daily).
     
    Argos, IrvineLee, d23z and 2 others like this.
  3. pospi

    pospi

    Joined:
    Oct 22, 2009
    Posts:
    3
    Oh. Really?! I swear I did test that. Thankyou so much for the quick response, i'll go hang my head in shame now :)