Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by adamss · Mar 16, 2016 at 12:38 PM · c#eventsarchitecture

What´s the cleanest way to link physics-events and gameobjects?

I'm looking for the "proper" way to organize my event handling code. I have a 2D game that detects mouseclicks on GameObjects with

  RaycastHit2d[] hits = Physics2D.RaycastAll(...)
  foreach(var hit in hits){
      // do something with hit.transform.gameobject
  }

I like this approach for its efficiency and flexibility for filtering of objects hit. My problem is, how do I route the click event back to a specific component? The example above works fine if I have one component called ClickHandler with a method CustomClick() that contains all the game's click logic.

 hit.transform.gameobject.GetComponent<ClickHandler>().Clicked(); 

But this is too simplistic; my game has several different components - terrain, buildings, animals, players - each needs to respond to a click in its own way. I want to avoid a mess of if statements :

  foreach(var hit in hits){
      if (hit.transform.gameobject.tag == "Terrain"){
          hit.transform.gameobject.GetComponent<Terrain>().Clicked()
      } else if (hit.transform.gameobject.tag == "Animal"){
          hit.transform.gameobject.GetComponent<Animal>().Clicked()
      } else {
         // ugh, repeat for each type, and remember to maintain this when new types added
      }
  }

The above works, but it's hardly elegant coding. Also, I'm using tags just as an example - in reality I can't assume an objects tag always corresponds to its event behavior. Unity's components don't do interface casting. I can use gameobject.SendMessage("Clicked"), but that's a performance killer. Any suggestions for a clean, fast solution to this?

Comment
Add comment · Show 1
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 Brocccoli · Mar 16, 2016 at 02:07 PM 0
Share

If it suits you, all those objects are obviously actionable on a click event.

If you made an interface, say, ClickableObject that had a single method ClickableObject.Click(), then you could cast whatever gameObject that is hit to a ClickableObject and call its Click() method.

You'd have to evaluate your own design and see if this works for you, but it's definitely a solution. You should be able to call

 hit.transform.gameobject.GetComponent<ClickableObject>();

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Bunny83 · Mar 16, 2016 at 03:31 PM

You can do interface casting. However Unity's generic GetComponent method has a constraint on "Component". So you can only use type parameters which are derived from Component which interfaces of course aren't.

I've posted two extension methods over here which essentially do exactly the same as Unity's generic method, but don't have the constraint.

As you might know you just have to create a static class somewhere in your project and insert those two methods in that static class. Now you can use those methods on any Component or GameObject reference.

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 · Mar 16, 2016 at 03:41 PM 0
Share

o.O I just had another look into the UnityEngine.dll of the latest Unity version and it looks like they actually removed the constraint. They also doesn't do a simple as-cast as they did in the past, but use some hacky unsafe code to perform a fast cast by doing some pointer tricks ^^.

So it's possible that the current version of GetComponent<T>() does support interfaces now. I haven't tested it though. Anyways my extension methods will work with any Unity version.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Question about unsubscribing eventhandlers OnDisable and OnEnable 2 Answers

Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer

controller/manager architecure 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