CameraKit2D icon indicating copy to clipboard operation
CameraKit2D copied to clipboard

Fix errors using GetComponents with an interface

Open shayded-exe opened this issue 10 years ago • 5 comments

Now uses the non-generic version of GetComponents then casts back to the proper type.

shayded-exe avatar Aug 30 '15 01:08 shayded-exe

Actually this doesn't quite work right. The GetComponents are returning null. Will update with a real fix.

shayded-exe avatar Aug 30 '15 01:08 shayded-exe

Aaaand there we go. The cast is now done per-element using Array.ConvertAll. The old method would just cast the whole thing.

shayded-exe avatar Aug 30 '15 01:08 shayded-exe

I've extracted out the extra code around GetComponents to an extension method.

I wont put it in the pull request, but you can use it if you wish :)

public static T[] GetInterfaceComponents<T>(this Component parent) where T : class
{
    return System.Array.ConvertAll(parent.GetComponents(typeof(T)), c => c as T);
}

shayded-exe avatar Aug 30 '15 07:08 shayded-exe

I am not sure I am following this. GetComponents works fine with interfaces as of Unity 4.6

From the release notes: Added smart-allocating GetComponents<List> method which fetches components of type T and grows the list as needed. Non-generic version that supports interfaces has also been added.

prime31 avatar Aug 31 '15 01:08 prime31

Strange, your normal code didn't compile for me because of GetComponents, so that's why I did this. I'm using 4.6.7.

shayded-exe avatar Sep 02 '15 04:09 shayded-exe