Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    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.
unityunity