delegates allow you to work out what function is going to be called at runtime. Without them you have to know the specific function at the time of writing/compiling the code.
In such a simple example you wont see the advantage. But consider something more complex where you want the action that is executed to be based on the runtime situation. For example, the effect that occurs when you click the “currently equiped item” button, that would depend on the functions of the item at that moment, which will vary and cannot be catered for easily and flexibly at the time you are writing the code.
The way I learned how delegates work was via callbacks. You can create a function that does some work, and then when that work is done, calls a function - but you get to specify the callback function. This can be especially handy with coroutines and/or threading. Here’s a coroutine example where you have a function that loads a page through the WWW class, then calls a callback with the resulting text.
public delegate void OnLoadCallback(string text);
public void ProcessWebText(string text) {
Debug.Log("Loading completed. Text is: "+text);
}
public IEnumerator LoadWebpageWithCallback(string url, OnLoadCallback callback) {
WWW loadingWWW = new WWW(url);
yield return loadingWWW;
if (callback != null) callback(loadingWWW.text);
}
void Start() {
StartCoroutine(LoadWebpageWithCallback("http://foo.whatever", ProcessWebText) );
}
This becomes even handier if you use Lambda functions - functions that are created inline, right in the middle of the function call. The syntax is a little weird, but the convenience is worth it. The following code does exactly the same thing as the above:
void Start() {
StartCoroutine(LoadWebpageWithCallback("http://foo.whatever",
(text) => {
Debug.Log("Loading completed. Text is: "+text);
}
);
}