Delegate Pt.3- C# Skill in Unity: 12

Objective: learning the basic use of lambda.

The last part of learning delegate is using lambda. Lambda is an expression that allows you to create methods in lines without taking times to create one besides the origin method.
Lambda also have lots of extended way to use, which will also be introduced in this tutorial.


To understand how to use lambda, the best way is adjusting an existing method.
Let’s use the example of Action in the previous tutorial to create a lambda expression.

The purpose of using lambda is to make the function in RunMethod() can also be processed without the method.
Here is the quick explaining of how to use lambda:

Let’s start adjusting these codes.
Here is how it would look like after using lambda:

And the result would be absolutely the same.

We can also open the parentheses to run more lines of code in lambda.

Using parameters in lambda

We can also pass in parameters to a lambda expression.
Let’s change some part of our code to use a parameter in it.

When pass in the parameter, no matter what contents that input to the small brackets, it would be recognize as the type of parameter that you use to declare a delegate.
And the result would be the same as creating a method.

Using lambda as return type method

As using to a return type, pass all parameters into small brackets and it should runs smoothly.
This is a short example reveals how to do a calculation in lambda:

We can also open the parentheses to reassign the integer in it.
However, if we do this with return type, we need to use “return” to send back the value.

Callback system

We can also use lambda to create a simple callback system.
Let’s create a coroutine, and run a delegate after 3 seconds.

However, this should cause some error since there is no delegate passing in.

We can set the onContinue to null as an option to pass in. This should fix the error in Start().

Now we can use lambda in Start() in the calling of coroutine to run some code after it.

And you should see the text after 3 seconds when hit Play.



A passionate gamer whose goal is to work in video game development.

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
S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.