The official Unity manual has this example of delegates.

public class DelegateScript : MonoBehaviour { delegate void MyDelegate(int num); MyDelegate myDelegate; void Start () { myDelegate = PrintNum; myDelegate(50); myDelegate = DoubleNum; myDelegate(50); } void PrintNum(int num) { print ("Print Num: " + num); } void DoubleNum(int num) { print ("Double Num: " + num * 2); } 

Not entirely clear - after all, we can get this conclusion elementary.

  void Start () { PrintNum(50); DoubleNum(50); } 

Please explain why they are here and whether they are needed in such situations at all;

  • For example, depending on the conditions, you want to call only one of the functions, and, depending on the others, the other. Therefore, somewhere (for example, in Update) you can write myDelegate (50) and it will call the desired function (the one that you assigned to it in the condition). In general, it would be nice to have a link to the page, otherwise it is not enough what it says there ... - Valera Kvip
  • unity3d.com/learn/tutorials/topics/scripting/delegates Ie I correctly understood that the delegates in this case perform a role similar to the getters and setters - it is assumed that they are like a layer between the method and the one that applies to it. And in this layer, you can enter your conditions. Right? - Dmitrii
  • not. They just showed the possibilities, and how to use your business. - Valera Kvip

1 answer 1

For the same reason that they are in C #.

You can read MSDN and understand their need and why they were invented.

In short:

A delegate is a handy wrapper for pointers to functions in C ++.

For example, you can make one of the arguments of the method delegate.

When calling methods, we pass a delegate to the method that points to the desired function, and inside the method we can call that delegate.

Delegates are also used in events.

UPD

In general, Unity uses all the language features of C # and it is obvious that almost all the functionality is available in Unity.

And to use or not use the full opportunity of the language you decide

With the same success, you can, how to use the concise capabilities of LINQ , which themselves generate the necessary code in the IL code, or you can use the foreach and iterate the collections yourself, but this will be somewhat less concise ...

Ie language gives you opportunities, and you manage them.