Delegate Pt.2- C# Skill in Unity: 11
Objective: continuing with more extended way of using delegate.
In this tutorial, we would continue digging more functions of delegate.
Action of void type
As declaring a delegate, we used at least 2 lines of code. Well, “Action” can help you create a void type delegate easily with one line.
Before we using “Action”, we need to add the namespace of “System”.
Then declare delegate with Action<>.
The “Action” declaration is actually replace:
public delegate void GetDamage();
public GetDamage getDamage;
If we need to give it a parameter, we can declare the type of action with T-bracket.
And it allows user to declare multi parameters.
Here is the example of using integer as parameter:
You can also set it as a static and an event delegate with action.
Then you can access it easily from other scripts.
Return type of delegate
So far we have known the basic of void type delegate. Besides that, it can also be declared as a return type delegate.
The way of declaration is pretty much the same as setting a return type method.
In here, we have declared a delegate would return integer and using string as parameter.
Then we can assign this delegate to another method that also contains a return type with integer, and using string as parameter.
Now we just need to run “characterSum” with a string in Start(), we could count how many characters with that string.
Then we can print it out with Debug.Log() to check the delegate runs perfectly.
Func of delegate
Same as void type, return type delegate also has a shorten way to declare, is called “Func”.
Pretty much the same pattern as Action, we can declare a return type delegate with 1 line only. And same as Action, it can contain multiple parameters and also requires namespace “System”.
However, you would need to notice the rule of declaration when using Func: you need to pass in the type of parameter first, then the return type.
As the example of return type delegate, the rest of code would run smoothly with the declaration of Func.