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 /
This post has been wikified, any user with enough reputation can edit it.
avatar image
7
Question by MaT227 · Aug 26, 2015 at 08:11 AM · c#eventsdelegateslisteners

Unity Events, Listeners, Delegates, etc.

Hey everyone,

I have some difficulties about understanding all the differences and usages of Unity Listener, Unity Events, Delegates, C# Events.

Could someone help me a bit about clarifying this ?
Thanks !

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

1 Reply

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

Answer by Eudaimonium · Aug 26, 2015 at 10:36 AM

You can think of an event as a "container of functions", like a box where other classes can put their functions in. When an event is "fired", all functions in there will be executed.

For example I have an event in my game called OnSave, which is fired when a Save Game procedure is started.

Syntax

Delegate is basically saying "This kind of functions can be subscribed to an event (be put into the container, if you will)". Here's my specific code example, in a public singleton class called GlobalControl:

     public delegate void SaveHandler(object sender, EventArgs e);
     public event SaveHandler OnSave;
 

This basically says:
Delegate is like a "blueprint", which describes a format of a function. My delegate says:

  • Function returns void

  • Function has two arguments, object and eventargs

Next, I say: This is a new event called OnSave. It can accept functions that match the delegate called "SaveHandler".

How this works:

Consider a player opening a chest in the game, and chest spawns 3 swords. Each sword (or LongswordDroppable object) says:

 public void Start()
 {
      GlobalControl.Instance.OnSave += MySaveFunction;
 }
 
 public void OnDestroy()
 {
     GlobalControl.Instance.OnSave -= MySaveFunction;
 }
 ...
 
 public void MySaveFunction(object sender, EventArgs e)
 {
     //Save this sword in the list of objects that should be spawned when level is loaded
 }

Translation:
At Start() function, each sword says "OK, I have a function that matches a delegate (it has required arguments, object sender and EventArgs), and I'd like to put that function into OnSave box)".

OnDestroy() function says: "OK nevermind, I would like to take my function out of the Save box, since I will be destroyed".

So after three swords are spawned, you can imagine the OnSave event now has three functions registered:

  • Sword1's MySaveFunction

  • Sword2's MySaveFunction

  • Sword3's MySaveFunction

Suppose player picks up the second sword, then saves the game.
Now there are only two functions in the Save "box of functions"

  • Sword1's MySaveFunction

  • Sword3's MySaveFunction

To execute all registered functions, you can call the following:

         if (OnSave != null)
             OnSave(null, null);

This basically says:
"OK time to save, now, do we have any functions registered at all? If so, let's go through them:

Sword1, you now execute your MySaveFunction. I'll wait. OK done?
Sword3, you now execute your MySaveFunction. Done?

OK this is it for the event, now we can continue with the code".

NOTE You can only fire the event from the class that contains the delegate and event declaration. In other words, ONLY GlobalControl can call OnSave(argument, argument). If you try to do from somewhere else: GlobalControl.Instance.OnSave(null, null); You will get a compiler error.

Just one more note I am using two arguments for the delegate (and hence all subscribed functions), object and EventArgs simply because they are mandatory by Mono/.NET framework, but I don't really need them, so I'm just passing "null" values. If you want you can actually pass some useful values, by constructing your EventArgs structure and filling it with some useful data if you need to.

Final note, swear to spirits of Palaven As to the other part of your question, Unity Events and Unity Listeners are basically this exact same thing, only premade (already declared events that you can subscribe to). You may have even used this without realising:
If you have used buttons in your UI, when setting their OnClick function, you basically subscribed a function to an OnClick event that was created when you put the button in your scene.

This is how you can have multiple functions subscribed to the same OnClick (or what have you) event.

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 Eudaimonium · Aug 26, 2015 at 10:51 AM 1
Share

Oh, I forgot to address a part of your question. Unity Events and Unity Listeners are basically this exact same thing, only premade (already declared events that you can subscribe to). You may have even used this without realising:
If you have used buttons in your UI, when setting their OnClick function, you basically subscribed a function to an OnClick event that was created when you put the button in your scene.

This is how you can have multiple functions subscribed to the same OnClick (or what have you) event.

avatar image MaT227 · Aug 26, 2015 at 12:22 PM 0
Share

Thank you @Eudaimonium for your very precise answer. I suggest you to edit your answer to add what you just said in the comment as it's part of the answer. :)

avatar image Eudaimonium · Aug 26, 2015 at 01:00 PM 3
Share

Done, @$$anonymous$$aT. , I hope I helped you understand this. I hate when something useful and fun to use, such as Events or other program$$anonymous$$g/sciency topic is constantly being explained the wrong way around or not explained at all, just re-typed official documentation or what have you.

If everybody just stopped abusing Copy-Paste for a second and actually explained it in their own natural tone as if we're sitting in a pub, world would be a better place :p

avatar image MaT227 · Aug 26, 2015 at 01:14 PM 0
Share

Agree @Eudaimonium, Thank you again !

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

29 People are following this question.

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

Related Questions

Question about unsubscribing eventhandlers OnDisable and OnEnable 2 Answers

How do Delegates and Events work? 1 Answer

Does calling Destroy() on a GameObject/MonoBehavior drop references to any event listeners? 1 Answer

Stack Overflow error on delegate call 2 Answers

Multiple Cars not working 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