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

Top 10 Tools for DevOps

Bridging the Gap Between Business Analytics & DevOps

Kotlin vs. Scala: Which is Right JVM for 2020?

Legacy system modernization with DevOps

Data Analysis with R — Part 1 (Getting Started)

Install and Configure ElasticSearch in Linux

Backend-in-the-frontend: a pattern for cleaner code

I’ve Had It With These Motherf**king Immutable Tuples In This Motherf**king Programming Language

A plane

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

Post Processing Primer for Unity

Getting Started with Unity’s URP and Skyboxes

Wall Jumping

Unity New Input System