GetComponentsInChildren also returns the component requested from the parent object as well as it’s children. Is there a way I can only get the children’s components? UnityScript preferable.
I disagree that UnityScript is preferable, because you can’t write extension methods with it. Here’s a method that allows you to choose just how deep in the hierarchy you want to pull components from:
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
public static class TransformExtensions
{
/// <summary>
/// <param name="skipChildren">How many child levels deep to select from</param>
public static T[] GetComponentsInChildren<T>
(this Transform transform, int skipChildren, bool includeInactive = false)
where T : Component
{
if (skipChildren == 0)
return transform.GetComponentsInChildren<T>(includeInactive);
skipChildren--;
return transform.Cast<Transform>().SelectMany( child =>
child.GetComponentsInChildren<T>(skipChildren, includeInactive) ).ToArray();
}
}
Then you could use it like this:
transform.GetComponentsInChildren<TypeOfYourComponent>(1);