The function works well but i get back all the childrens and the father too. Mamely, i get back this “this.gameObject” too and i don’t want this. How can i get only the childrens?
Using System.Linq gives you access to the Where extension and then you can run a search. You can read more about Linq here: Understanding LINQ (C#) - CodeProject, but you are basically running a search on everything returned by GetComponentsInChildren and only adding it if the search is true.
Although, it would be more efficient to use your code without Linq, and then run your loop like this:
foreach(Transform t in SceneObjects)
{
if(t != this.gameObject.Transform)
{
//... Your code
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class UtilityExtensions
{
public static T[] GetComponentsOnlyInChildren<T>(this MonoBehaviour script) where T:class
{
List<T> group = new List<T>();
//collect only if its an interface or a Component
if (typeof(T).IsInterface
|| typeof(T).IsSubclassOf(typeof(Component))
|| typeof(T) == typeof(Component))
{
foreach (Transform child in script.transform)
{
group.AddRange (child.GetComponentsInChildren<T> ());
}
}
return group.ToArray ();
}
}
Then all of your Monobehavior scripts can use it and not only for Transforms, but for any type of component or interface. (yes GetComponent can also get Interfaces!)
if an invalid type is passed in or if there aren’t any of that type in the children, it will return an empty array.
EDIT: I missed the part about only direct children (excluding any further descendants). in that case the code for that isn’t that much different from what I already wrote, just swap out the GetComponentsInChildren<T>() with GetComponents<T>()