Hi I have the following extension method
public static T[] GetComponentsOfType<T>(this GameObject source) where T : MonoBehaviour
{
Component[] matchingComponents = source.GetComponents<Component>().Where(comp => comp is T).ToArray();
T[] castedComponents = new T[matchingComponents.Length];
for (int i = 0; i < matchingComponents.Length; i++)
{
castedComponents[i] = (T) matchingComponents[i];
}
return castedComponents;
}
Which works completely fine however I tried to shorten it by just a single line
return (T[]) source.GetComponents<Component>().OfType<T>().Cast<Component>().ToArray();
And apparently this line fails to cast the Component[] to T[] but when I cast each element separately it works (the first example). Why is that ?
Component[], that isn't aFooComponent[]or whateverTis. Why not just useOfType<T>().ToArray()? Why are you callingCast<Component>()?Cast<Component>()doesn't make sense. If you wantT's, why cast it toComponentagain?