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.

Player.cs
UIManager.cs

Pretty simple:)

Using the Lambda expression, we can avoid using a seperate method.

Func

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.

--

--

--

Unity Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How can we provide internet access to instances in private subnet(NAT Gateway,Bastion host)

Why NOT going to conferences is costing you too much

Grid Alignment — Grid Series Part 2

Tech Lead Handbook — Consensus vs Consent

AvacusApp is now fully support Solana network!

Remove a local user on Windows-like systems — Ansible module win_user

Pod Security Policies are dead, long live Pod Security Admission!

OTOMotors Mod Kits Will Change the Game

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ali Emre Onur

Ali Emre Onur

Unity Developer

More from Medium

Converting from 3D to 2D in Unity

Unity New Input System

Platformer: Wall Jump

Framing Transposer Virtual Camera Explained in Unity’s Cinemachine