Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
4
Question by Agustin Petrini · Jan 21, 2011 at 04:43 PM · component

How to get the first component that implements a specific interface ?

Is there a beter (more style / more performant) way of getting the first (and hopefully only) component that implements a specific interface ?

public interface IFoo { void iFooMethod(); }

public class Foo { void OnCollisionEnter(Collision collision) { IFoo fooObject = null; MonoBehaviour[] components = collision.transform.root.GetComponents(); foreach(MonoBehaviour component in components) if(component is IFoo) { fooObject = component as IFoo; break; } if(fooObject != null) fooObject.iFooMethod(); } }

It just feels like I'm missing something ala GetComponentWithInterface.Blockquote

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

4 Replies

· Add your reply
  • Sort: 
avatar image
21

Answer by Andy-Block · Sep 22, 2013 at 08:27 PM

You can't use the generic method, but this form seems to work fine:

IFoo foo = (IFoo)gameObject.GetComponent(typeof(IFoo));

Probably too late for the OP, but perhaps this helps someone else :) .

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Teddy_p · Dec 02, 2013 at 06:32 AM 1
Share

YES! this was what i was looking for. very good! thank you. (i cant up-vote because i don't have enough reputation, sorry)

avatar image TastyWithPasta · Sep 09, 2014 at 02:28 PM 1
Share

Thank you very much! - Someone else

avatar image chris-nolet · Jun 20, 2016 at 07:47 PM 1
Share

You can actually use the generic method – gameObject.GetComponent<IFoo>() – in Unity 5 now, too :)

avatar image Andy-Block chris-nolet · Jun 20, 2016 at 08:04 PM 0
Share

@chris.nolet - nice, thanks for the info!

avatar image
14

Answer by chris-nolet · Jun 20, 2016 at 08:01 PM

As of Unity 5, you can use the generic form of GetComponent on interfaces:

 IFoo foo = gameObject.GetComponent<IFoo>();
 IFoo[] foos = gameObject.GetComponents<IFoo>();

Alternatively, .GetComponent(typeof(IFoo)) works for old versions of Unity and .GetComponents(typeof(IFoo)) (with an 's') also works from Unity 4.6 onwards.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Andy-Block · Jun 20, 2016 at 08:06 PM 2
Share

Shouldn't that be:

      IFoo[] foos = (IFoo[])gameObject.GetComponents<IFoo>();

For the second version?

avatar image chris-nolet Andy-Block · Jun 21, 2016 at 01:25 AM 0
Share

Quite right – thanks! I've updated the answer. $$anonymous$$uch appreciated!

avatar image
0

Answer by _Petroz · Jan 21, 2011 at 08:20 PM

I beleive that whole code block could be condensed down to the following:

void OnCollisionEnter(Collision collision)
{
    collision.transform.root.GetComponent<IFoo>().iFooMethod();
}
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Agustin Petrini · Jan 21, 2011 at 09:50 PM 0
Share

$$anonymous$$mhm no, that's what I tried originally but: The type IFoo' must be convertible to UnityEngine.Component' in order to use it as parameter T' in the generic type or method UnityEngine.Component.GetComponent()'

Which makes sense since an interface cannot be a$$anonymous$$onoBheaviour (a child of I mean).

avatar image _Petroz · Jan 21, 2011 at 10:12 PM 0
Share

I see what you mean, I didn't realize 'interface' had a special meaning in C#, I thought you were just referring to an abstract base class. In that case I think the code you have is the best you will get. All I could suggest is wrapping it in a function to reduce the boiler plate in the classes using this code.

avatar image Agustin Petrini · Jan 21, 2011 at 11:55 PM 0
Share

Yap, exactly what I did. The logic got a little more complicated so I moved everything to a new method in the superclass. Right now I don't think in my case a GetComponentsWithInterface() would help anymore, but kinda drives my attention that there's nothing to do it automagically. Cheers.

avatar image
0

Answer by josephquested · Aug 21, 2020 at 08:06 AM

y'all are making it way too complicated. this works perfectly:

 public class Hit : MonoBehaviour
     {
         void OnTriggerEnter(Collider other)
         {
             if (other.GetComponent<IDamageable>() != null)
             {
                 print("HIT INTERFACE");
             }
         }
     }


Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · Aug 21, 2020 at 08:23 AM 0
Share

You missed the point pretty much. Back then when the question was asked the generic version of GetComponent has a constraint to "Component". This made it impossible to use an interface as type argument and you had to use the System.Type version instead and cast the result. This is what Andy-Block's answer said. Later Unity removed the constraint to allow interfaces. This is what chris-nolet's answer said.


The question was about getting the first component with a certain interface in order to call a method on it. In which way are the other answers more complicated? In your answer you don't even call any method and just check if such a component exists. I also don't see how this is any new information compared to the answer of chris.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

2D Animation does not start 1 Answer

What is the syntax for adding some generic type of component without an object reference? 1 Answer

Destroy(GetComponent(...)) not working 1 Answer

Retrieve gameobjects from a network.player, adding multiplayer components 1 Answer

Vehicle Upgrade System 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges