delegates can help you write cleaner more modular and more functional code.
Delegates are defined as a function signature and return type but without any implementation.
1
2
3
4
5
6
7
8
9
10
11
12
13
publicdelegatevoidTestDelegate();//returns void, takes no paramsprivateTestDelegatetestDelegateFunction;privatevoidStart(){testDelegateFunction=MyTestDelegateFunction;testDelegateFunction();}privatevoidMyTestDelegateFunction(){Debug.Log("test");}
Like events you need to subscribe delegates to functions. you can do this with =.
Make sure everything matches the right signature.
you can subscribe different functions to delegate with different behaviors, this can allow for nicely decoupled code.
!! when you define a delegate you need to give a name to the parameter, so just putting int won’t work.
However, when you define a delegate function you don’t actually have to use the same name.
!! Under the hood: when we assign a delegate it’s actually doing this