• 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 Disaster · Apr 24, 2011 at 02:53 PM · getcomponent

GetComponent and interfaces

I want to create a set of different 'movement' scripts which I can apply to my games units. Each class will have different calculations for moving the unit around the screen, I am attaching these classes to my Unit GameObject. I want to be able to enable and disable the movement class when it has finished movement calculations so that it isn't working away unnecessarily.

The problem here is that in order to call the enable method, my Unit GameObject must have a reference to the Movement class, but since this class can be a one of many, I can't specify which one it will be.

I tried to solve this by giving my movement classes an interface, IMovement, but GetComponent is only referencing the interface itself and not the class, so I am unable to set the enable property.

The only other solution I can think of is to use class inheritance, but having each method marked as an override is a pretty messy solution.

Anyone have any ideas?

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

3 Replies

· Add your reply
  • Sort: 
avatar image
5
Best Answer

Answer by superpig · Apr 25, 2011 at 12:04 AM

Just cast it:

Component movement = (Component) GetComponent<IMovement>();
movment.enabled = true;

It's a bit unpleasant because there's now the implicit requirement that all IMovement implementors be Component-derived, and no enforcement of that, but it sounds like you were considering that as an alternative solution anyway.

Comment
Add comment · Show 5 · 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 Rafes · Aug 20, 2011 at 10:12 PM 0
Share

I don't think this works since interfaces do not inherit from Component. I am still looking for an easy way to do this. Going with a base class rather than an interface is looking more and more like the only answer.

avatar image Kryptos · Jun 26, 2012 at 11:19 AM 5
Share

If you want ot use interfaces, you must use the non-generic method:

 Interface myInterface = (Interface) GetComponent(typeof(Interface));
avatar image blutderengel · Jan 07, 2014 at 04:12 AM 0
Share

Thanks for that input $$anonymous$$ryptos. I used your feedback to implement functionality where an object will apply damage to another object upon collision. I do this by finding the component that implements the interface I wrote 'IDamageable', where each implementing component is responsible for deter$$anonymous$$ing what to do when it takes damage.

In case this may be useful to others, an example:

 void OnTriggerEnter( Collider aCollider )
 {
     IDamageable component = (IDamageable) aCollider.GetComponent( typeof(IDamageable) );
     if( component != null )
     {
         component.ApplyDamage( CalculateDamage() );
     }
 }
avatar image glantucan blutderengel · Nov 05, 2015 at 07:10 PM 3
Share

It seems you can get components implementing a particular interface now (since Unity 5 ?) like this:

 I$$anonymous$$ovement movement = GetComponent<I$$anonymous$$ovement>();

It's not necesary to cast the object returned by GetComponent anymore. What I'm wondering about is how efficient is this. But at least looks neater than before in you code ;)

Regarding the enabled property, have you tried to declare it in the interface like this?

 public interface I$$anonymous$$ovement {
    bool enabled { get; set; }
    //...
 }

avatar image Bunny83 glantucan · Nov 05, 2015 at 08:19 PM 1
Share

Yes, it looks like they removed the "Component" constraint from the generic type argument. So now GetComponent<T> will work with any type. Of course it only makes sense using class types which are derived from Component or interfaces.

avatar image
1

Answer by Uzquiano · Apr 24, 2011 at 03:03 PM

Hi,

Well, my suggestion would be that you should take advantage of the component-oriented architecture Unity provides... In other words, I would put each of your classes in a different script, in this way you coudl use easily GetComponent(aMovementScript).

But this is just my suggestion.

Hope this can help you

Comment
Add comment · 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
7

Answer by ckfinite · Apr 24, 2011 at 03:17 PM

If you are working in C#, you can require property setters and getters through the interface. With this, you could do this:

public interface IEnableable {
     bool Enabled { get; set;}
}

and for the implementation

public class aMovement : MonoBehaviour, IEnableable
{
    public bool Enabled {
        get {return enabled;} 
        set {enabled = value;}
    }
}

you could also do this with a abstract class.

Comment
Add comment · 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

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Can't Call function in another script 1 Answer

How am I supposed to use GetComponent? 1 Answer

Unable to assign prefabs target at runtime 1 Answer

Can someone help me fix my Javascript for Flickering Light? 6 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