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
0
Question by overki11 · Feb 04, 2016 at 09:40 AM · c#eventsfunction call

[C#] Am I using events right?

Hello. I've been trying to get into the practice of using events, but I'm not sure I'm using them exactly right.

Let's say I have an event that should be called whenever the player loses health. What I have been doing is subscribing to the event with the function for losing health, and whenever I want the player to lose health I call the event. Should I be calling the event whenever the lose health function is called instead? Here are a couple examples with the two workflows to show what I mean:

Example 1:

Function1 subscribes to event

Function2 needs function1 to be called, so they call the event rather then calling the function itself.

Example 2:

Function1 calls event inside of it's code.

Function2 needs function1 to be called, but since function1 has a call to the event in it's code, it simply calls function1, calling the event at the same time.

So, with all that said, which way is the "right" way? Are they both okay? If one of them is more efficient, which one?

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 npatch · Feb 04, 2016 at 10:24 AM 0
Share

Don't exactly understand the examples, next time provide some example code. $$anonymous$$akes it easier than trying to understand "function that needs function that calls function with function".

Let me give you another using the same premise of being interested on player health loss..

You subscribe/register callbacks of interested classes/entities/whatever to an event. Basically an event is like a list of functions to call when something happens. Functions that can be from any script. Also the event raising(the term for calling the event and notifying the interested) happens where the event happens in reality. So in the case of damage being applied, you will raise the event right after you subtract the damage to the remaining health.

 class Player{
 public delegate void HealthLostDelegate(float);   
   public event HealthLostDelegate HealthLost;
   private float remainingHealth;
 
   public void ApplyDamage(float damage){
     remainingHealth -= damage;
     if(HealthLost != null){
        HealthLost(remainingHealth);
     }
   }
 }
 
 class HealthHUD{
   void Start(){
     FindObjectByType<Player>().HealthLost += UpdateHealth;
   }
 private void UpdateHealth(float newHealth){
    someTextComponent.text = newHealth.ToString();
  }
 }

This is very hastily written so there might be mistakes here and there but this is more to show you the logic.

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by SUpersindit2 · Feb 04, 2016 at 10:26 AM

Lets say we have a function Called A subscribed to the event function Called E, all we need to do is call E() and it will execute all the subscribed functions which is A.

However you must be mindful that in the case of no subscribers in the event and you call it, it might cause memory leakage, so you must check that the event E != null before calling it.

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
0

Answer by cjdev · Feb 04, 2016 at 10:45 AM

The first example is the idea of events. Another way to think of it is not as if one method is calling another but as if methods are saying they want to do something when some conditions occur. When an event is called it's called by some unrelated and unknown method to those waiting for it, which is the idea: to decouple the links between objects and make them easier to work with. This way you don't need to change all your classes if you change one of them just because they all reference a method in it.

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 npatch · Feb 08, 2016 at 09:05 AM 0
Share

Not only that, it relieves you from having to check for boolean flags inside Update functions as well, what we call Polling. Booleans tend to increase if you don't use events and they also tend to create massive State diagrams where you need to check what happens when one is true and another is false for an array of booleans.

But, there are drawbacks as well. If you connect , by chance or otherwise, a long list of listeners that adds to many layers in depth, you WILL see spikes here and there in the game. You have to do some polling as well. Use event queues and a dispatcher in order to decouple the call stack from the actual point of the event raising to release the script that raises the event from the big call stack that will be created from the event being raised.

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

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How can I make Unity's overridable events appear within the Intellisense dropdown in Visual Studio (C#)? 1 Answer

Invoke/Coroutine problems with events 2 Answers

How to subscribe method to OnDisable in a gameObject. 1 Answer


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