Actions and Func In Unity
On my previous article, I have explained Delegates and Events in Unity. Well, Actions are basicly the delegate and the event together. As I have mentioned earlier, we use events in order to add a protection layer to the delegate. Actions are also delegates, but they are already type-safe — thus, eliminating the need for using an event.
In order to declare an Action, we need to add “using System” line to the namespaces. Certainly, to prevent the need of creating an instance, we also define the Action with the static keyword.
public delegate void OnDamage;public static event OnDamage onDamage;
The delegate and event defined above will provide the same result as defining an action as below:
public static Action OnDamage;
However, if we want to provide a parameter within the Action, we need to use <> rather than ( ).
In the example below, I have created a prototype in which the UI Manager decreases the health once the Player gets damaged.
Using the Lambda expression, we can avoid using a seperate method.
When it comes to the return type delegates, the “Funk” keyword needs to be used rather than Action.
While defining a Func, you will notice that we can define it with or without parameters. For instance, an example will be provided below that will provide the length of a string.
The same result can be achieved using Lambda operator rather than using the Count method:
Since the CharacterCount Func is defined as taking a string as a parameter which returns an int, we simply tell that take the name (string variable) and return the length of it as int — which is compatible with the Func type.
Simple Callback System
We can create a simple callback system as below:
The Action will be called once the routine is finished.