Jump to content
Unity Insider Forum

GameObject.GetComponentsInChildren<T>() optional ohne Parent


devandart

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ß

Link zu diesem Kommentar
Auf anderen Seiten teilen

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Gast
Auf dieses Thema antworten...

×   Du hast formatierten Text eingefügt.   Formatierung jetzt entfernen

  Only 75 emoji are allowed.

×   Dein Link wurde automatisch eingebettet.   Einbetten rückgängig machen und als Link darstellen

×   Dein vorheriger Inhalt wurde wiederhergestellt.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Lädt...
×
×
  • Neu erstellen...