Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    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:
    171
    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

    Unity Technologies

    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:
    171
    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 :)