Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Finding all script components in scene which implement a specific interface.

Discussion in 'Scripting' started by kevroy314, Apr 3, 2014.

  1. kevroy314

    kevroy314

    Joined:
    Aug 13, 2013
    Posts:
    3
    I've got an object which is going to perform some logging for me. I have an interface called ILoggable which I implement in a few different logging classes for different types of objects. These scripts are attached to objects whose details I would like to log.

    I place a Logger object with a Logger script in the scene, and I want it to, on Start, populate a list of any objects which currently exist which have scripts components which implement ILoggable.

    I've tried a few different things. The closest I've gotten is making the Logger GameObject the root of the entire game tree (I don't like this, but it at least does something), then call this.GetComponentsInChildren<SimpleLogger>(); . I can't call it on ILoggable without a compile error.

    Has anyone done this before? I imagine I'm just missing something fundamental, but I'm not sure what it is.
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Code (csharp):
    1.  
    2. GetComponent(typeof(ILoggable));
    3.  
    Will work so
    Code (csharp):
    1.  
    2. FindObjectsOfType(typeof(ILoggable));
    3.  
    might work as well.
     
  3. kevroy314

    kevroy314

    Joined:
    Aug 13, 2013
    Posts:
    3
    GetComponents(typeof(ILoggable)) never seems to return for some reason. FindObjectsOfType(typeof(ILoggable)) returns null. Any other suggestions? I appreciate the help by the way!

    Edit: It actually might be just throwing an exception when I try to cast it to an ILoggable[] .
     
    Last edited: Apr 3, 2014
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    It is sort of a bummer that this type of thing isn't easier when it comes to interface implementation. What I've done when solving this is create an abstract class that derives from MonoBehavior and implements a specific interface and then "get" that abstract class.
     
  5. kevroy314

    kevroy314

    Joined:
    Aug 13, 2013
    Posts:
    3
    Yeah I'm kinda disappointed. It seems like the only way I'm going to be able to do it is if I can somehow populate a list of all script components and manually filter out the ones that aren't ILoggable. I'm not sure how to do that at this point, but it seems like the only real option. I could do an abstract class, but it's not a very good abstraction of the sort of behavior I want. The object isn't a Loggable, it has Loggable functionality.

    Anyway, thanks for the help! I'll post back if I figure something out.