Reputation: 75
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 ?
Upvotes: 0
Views: 56
Reputation: 22038
You should make use of the OfType<>
only. In your solution, you are it back to Component
, which can't be cast to T[], so thats the problem.
The OfType<>
already casts it. It's like a substitute for Where(item => item is T).Cast<T>()
return source.GetComponents<Component>().OfType<T>().ToArray();
Upvotes: 2
Reputation: 12619
You can write:
source.GetComponents<Component>().OfType<T>().ToArray();
To do it in one line.
The cast fails because you are casting two types that do not match and Array of component to and array of T and that is invalid.
Upvotes: 2