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
  2. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  3. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

FindObjectsOfType and GetComponents behaviour mismatch regarding interfaces

Discussion in 'Experimental Scripting Previews' started by pixelsplit, Oct 17, 2016.

  1. pixelsplit

    pixelsplit

    Joined:
    Sep 16, 2013
    Posts:
    173
    Hi,

    silently in the past it became possible to use GetComponent on interfaces (so the constraint on MonoBehaviour got removed) - this is a GREAT thing! However i would also expect this behaviour from FindObjectsOfType, so I could also use this method on interfaces. However FindObjectsOfType<T> requires T to be a component (constraint).

    Can anyone explain why the behaviour is different (GetComponent vs FindObjectOfType) or if there will be FindObjectsOfType on interfaces in the future?

    Best regards,
    zkw
     
  2. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    In the meantime, you can do this:

    Code (csharp):
    1. FindObjectsOfType<Component>().Where(c => c is typeof(IWhateverInterface)).Select(c => (IWhateverInterface) c);
     
  3. JonHUnity

    JonHUnity

    Joined:
    Sep 16, 2016
    Posts:
    21
    Hi zkw,

    FindObjectsOfType and GetComponent are different in that GetComponent searches for Components implementing the given type underneath a specific GameObject, whereas FindObjectsOfType searches globally for any Object deriving from the given type.

    That said, you make a great point. Supporting interfaces in FindObjectsOfType seems like a great idea. We will be looking into this.

    Thanks!
     
    phobos2077 likes this.
  4. pixelsplit

    pixelsplit

    Joined:
    Sep 16, 2013
    Posts:
    173
    Hi,

    thanks for the explanation - now I get the different approaches of those methods. Would love to see this feature in the future!

    Thanks!
     
  5. shaderbytes

    shaderbytes

    Joined:
    Nov 11, 2010
    Posts:
    900
    2 years later... um..
     
    dithyrambs likes this.
  6. CulzeanImmerse

    CulzeanImmerse

    Joined:
    Nov 19, 2019
    Posts:
    1
    Another year and a half later, still looks like a nice idea, but no sign. Sigh
     
    dithyrambs likes this.
  7. ExtraCat

    ExtraCat

    Joined:
    Aug 30, 2019
    Posts:
    52
    Another year and a half later, still no. Unity doesn't like implementing great ideas, I see :)