Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

GetComponent doesn't work with covariance

Discussion in '2017.1 Beta' started by Deni35, Jul 2, 2017.

  1. Deni35

    Deni35

    Joined:
    Jul 10, 2012
    Posts:
    43
    I have a hierarchy:

    Code (CSharp):
    1.  
    2. public interface IA {
    3. }
    4. public interface IA<out T> : IA {
    5. }
    6. public class A : MonoBehaviour, IA<string> {
    7. }
    8.  
    Code (CSharp):
    1.  
    2. A obj = null;
    3. IA<object> baseObj = obj; // ok
    4.  
    5. typeof( IA ).IsAssignableFrom( typeof( A ) ); // true
    6. typeof( IA<object> ).IsAssignableFrom( typeof( A ) ); // true (only for .NET 4.6)
    7.  
    8. GetComponent( typeof( IA ) ); // ok
    9. GetComponent( typeof( IA<object>) ); // null
    10. GetComponent( typeof( A ) ); // ok
    11.  
    As you can see Unity can't find component by IA<object>.
    What do you use for comparing types?


    Also I want to draw your attention that GameObject.FindObjectOfType still is not working with interfeces.
    Could you remove checking for UnityEndine.Object?
     
    Freezing likes this.