Sunday, November 17, 2019

Unity3D events, delegates and Action


Delegates and events are very powerful features of C#. With them you can write clean and efficient code also in Unity.

However, I have found delegates bit confusing to understand. Most of the examples I have seen are not so easy to understand, especially if you are a self-taught coder like me. :)

Most of the examples I have found are using both delegate and event definitions. Something like this:
public delegate void PlayerHit(int damage); 
public event PlayerHit onPlayerHit; 

But personnally, I like using Action<> type instead. It allows you to replace two lines with one and it will make your C# code simpler. It also removes some confusing buzz around delegate definition. Here's an example:
public static event Action<int> PlayerHit;

So, at least for me this looks more understandable.

Please find below two very simple code snippets from my GitHub repository to see a real life example using Action in defining delegate. In this example event passes one integer, but you can have multiple parameters to an Action (just list your parameter types comma separated between <> characters).

TestPlayer class:

Manager class:
-Jussi

No comments:

Post a Comment