Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
2
Question by BilboStabbins · Jun 06, 2020 at 09:17 PM · eventeventsdelegatecallbackaction

When to use 'delegate', 'event' or 'Action' ?

Hi,

Can someone please provide a definitive explanation of when/in what circumstance to make use of each of these over the other?

I'd also be interested in hearing opinions on what the best practice might be moving forward (future Unity versions/new techniques, etc.).

Thanks in advance.

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
14

Answer by ShadyProductions · Jun 06, 2020 at 11:26 PM

A delegate is a type that can contain any method of the same compatible type. Delegates are used to define callback methods and implement event handling. Any method from any accessible class or struct that matches the delegate type can be assigned to the delegate. Example:

 public delegate int Calculate(int x, int y);

An example method that can be assigned to this delegate:

 public int Minus(int x, int y)
 {
     return x - y;
 }

An action is a premade delegate you can use without the need of making a custom one. Action by itself has no parameters, but you can have those with the generic Action<T> version

Examples:

 Action sayHello = () => { Debug.Log("Hello"); };
 sayHello();
 Action<string> print  = (a) => { Debug.Log(a); };
 print("abc");

Usage:

You can pass these to your own methods as parameter

 public void FindAndExecute(int number, Action toBeExecuted)
 {
      //search list for number, and execute the toBeExecuted method
 }

 // If 5 is in list, then player will die.. idk..
 FindAndExecute(5, () => { Player.Alive = false; });

You also have a few other premade delegates such as Func, which is the same as Action but with a return type like so:

 Func<string> getValue = () => { return "value"; };
 Func<string, bool> isValue = (a) => { return a == "value"; };

I often use Func as a custom criteria parameter to some methods that retrieve data.

Events are also of the delegate type, which use the observer type pattern. It allows a subscriber to register a method to an event, and be notified when the event is invoked.

Examples:

 public event EventHandler PlayerJoinedLobby;
 
 public void JoinLobby()
 {
     PlayerJoinedLobby?.Invoke(); //Any subscriber is now notified that a player joined the lobby (method is executed on all subscribed objects)
 }

 // Any class can subscribe to this event like:
 className.PlayerJoinedLobby += method;
 
 // Unsubscribe:
 className.PlayerJoinedLobby -= method;

Can be used to notify many listeners at once for a method to be executed. Why use events? It keeps your classes decoupled, (single purpose classes) which makes for more robust and clean code, and your subscribers won't affect the other class in anyway as they are independent on the behaviour of their subscribers.

All these topics are quite well explained on the microsoft docs, it is worth to check them out.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/ https://docs.microsoft.com/en-us/dotnet/api/system.action?view=netcore-3.1 https://docs.microsoft.com/en-us/dotnet/standard/events/

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 Olakehs · Feb 22, 2021 at 05:17 AM 0
Share

Hey mate, thank you for your explanation. Would you $$anonymous$$d provide some hypothetical game mechanic examples of when Action is inadequate and you need to defer to delegate? Thank you in advance

avatar image Llama_w_2Ls Olakehs · Feb 22, 2021 at 09:33 AM 0
Share

An action has no return type, unlike a delegate, which can return a variable. However, Func and Predicate return types as well, so they can be used when you need to return a variable from a function.


Remember that Action, Func and Predicate are all just pre-made delegates in the end. It doesn't matter whether you use them or not, instead of just delegate. At least, that's what I heard. @Olakehs

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

133 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 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 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 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 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

Can you use UnityEvents to invoke methods with parameters from other classes? how?,UnityEvents with arguments resulting in a lot of errors. UnityAction? how? 1 Answer

Navmesh event on navigation end 0 Answers

Question about subscribing to an event 1 Answer

Action delegate doesn't show in inspector. 1 Answer

Login form: Do I have to set custom delegates to null in OnDestroy? 0 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