Action Callback in Unity — Code Saying
Delegate is a famous way to implement Callbacks in C#. Action is one such generic delegate type. Action Callbacks can be very handy in Unity programming. Let us learn how to use Action Callback in Unity.
What is an Action?
Action is a generic delegate type defined in the System namespace. Action objects return no values. So we can say that Action type is similar to a void method. For example:
void Start() {
System.Action<string> printAction = new System.Action<string>(Display);
printAction("Welcome to CodeSaying");
} void Display(string message) {
Debug.Log(message);
}
Here, we have created an Action named printAction. Action<string> implies that the method assigned to this action should have one argument of type string. Consequently, a method named Display has been assigned to printAction. Note that Display() also has a string argument.
Another way of assigning method to an Action is by not using the new keyword
System.Action<string> printAction = Display;
printAction("Welcome to CodeSaying");
Using Lambda Expressions with Action in Unity
Instead of using a separate method to define the Action, we can use Lambda Expressions as follows:
void Start {
Action<int> printAction = i => Debug.Log(i);
printAction(10);
}
Using Action Callback in Unity
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action.
Delegate provides a way to pass a method as argument to other method.
For instance, we have to hit an API to get a response. In such case, we can use Action Callback. Let us see how:
void callApi() {
StartCoroutine(FetchData(ApiAction));
} string url = "https://postman-echo.com/get?foo1=bar1";
IEnumerator FetchData(System.Action<string, bool> callback) {
UnityWebRequest getData = UnityWebRequest.Get(url);
yield return getData.SendWebRequest();
if (getData.isDone == false || getData.error != null)
callback(getData.error, false);
else
callback(getData.downloadHandler.text, true);
} void ApiAction(string response, bool isSuccess) {
if (isSuccess)
Debug.Log(response);
}
Here, the Coroutine FetchData takes an Action type as argument which further encapsulates a method with two input parameters : string and bool. When this coroutine is invoked from CallApi function, the data is fetched from server and, the callback ApiAction is fired with response(string) and isSuccess(bool) as arguments.
We could have even used a lambda expression here to simplify the code:
void callApi(){
StartCoroutine(FetchData((response, isSuccess) => {
if (isSuccess) {
Debug.Log(response);
}
}));
}
Using lambda expression, we have defined what action should be taken on receiving the callback inside the callApi function without the need to define ApiAction function.
Drop in your queries in the comment section.
Happy Coding!
Originally published at http://codesaying.com on June 27, 2020.