Jump to content
Unity Insider Forum
Sign in to follow this  
devandart

GameObject.GetComponentsInChildren<T>() optional ohne Parent

Recommended Posts

Moin,

 

ich habe nichts dazu gefunden, darum poste ich hier mal eine Extension für GameObject.

Da Unity in der Methode GameObject.GetComponentsInChildren<T>() auch immer die Component aus dem Parent-Objekt zurückgibt, kann man es hiermit nun optional aktivieren/deaktivieren.

 

using UnityEngine;
using System.Collections;

public static class GameObjectExtensions {

   /// <summary>
   /// Searches all components in GameObject (optional) and it's children.
   /// </summary>
   /// <typeparam name="T"></typeparam>
   /// <param name="go"></param>
   /// <param name="includeInactive"></param>
   /// <param name="includeParent"></param>
   /// <returns></returns>
   public static T[] GetComponentsInChildren<T>(this GameObject go, bool includeInactive, bool includeParent)
   {
       T[] result = go.GetComponentsInChildren<T>(includeInactive);
       if (!includeParent)
       {
           T parentComponent = go.GetComponent<T>();
           if (parentComponent != null)
           {
               T[] componentsWithoutParent = new T[result.Length - 1];
               for (int i = 0; i < componentsWithoutParent.Length; i++)
               {
                   if (!result[i].Equals(parentComponent))
                       componentsWithoutParent[i] = result[i];
               }
               result = componentsWithoutParent;
           }
       }
       return result;
   }

}

 

Gruß

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×