After some years of coding, I found myself watching code with callbacks, and although I practiced several times and watched several videos, I couldn’t understand it well. Today I’ll write this blog in the hope of being useful for others

First, we need to see a common example

Piece of cake: First GetS3List is called, and later ActivatePanel. Common case.

Now, a callback, as I understood (If it’s not correct, please let me know), before continuing the program execution

W

If you see above, the code execution is:

  • Execute GetS3List

Later

  • Execute ActivatePanel

As you can see, we are executing 1 step, and after it’s done, we continue with the second step.

Now, let’s say I want the whole code (both steps, GetS3List and ActivatePanel) to be executed before continuing the program execution flow.

Normally, a method allow parameters as int, string, etc. and later it executes some code

And for instance, this won’t be allowed

Neither this

First, this AddValue declaration only as said before ()

Second, in AddValue, value , and below, , that is not allowed in this case

For these cases, the are the solution

Delegates is a special type of variables that allow you to assign a method to them. For example

www.tutorialsteacher.com/csharp/csharp-delegates

It assigns the MethodA to delegate variable

Or use a lambda expression to execute the code immediately

Example of implementing a Delegate

Now, we will use an

An Action can get a method as its value and execute it, without declaring a Delegate and later assigning a new variable

Action delegate can be used with anonymous methods or lambda expressions.

Much easier

Another example with less code but harder to read

Let’s say that in this example shown before, it executes one line and later the other one

Let’s say before continuing the program execution. Here is where the , well,

First, we need to modify the GetS3List method signature

The only way to verify if is not null is when the GetS3List method is called

The method execution (method call):

  • Starts in the orange line
  • Gets the caseNumberInput.text value
  • Executes the whole code contained in the Action (green area, strange but it’s the anonymous way)
  • Finishes after the second orange line

The objective is to execute the whole line of code and later continue the program execution, but maybe we want to execute the whole code but without stopping the program execution. That is why this Action execution (also called as a ) is executed as a
It means that the Action code will be executed in the background while the program continues its execution flow

Unity developer