Another Guy Explaining Delegates

You might be wondering; what are delegates? Probably not, because if you’re here, then you’ve already watched Ben’s video on it. Let me explain them to you anyway.

A delegate is a collection of methods. You can add or remove methods from this collection with the += and -= syntax. Calling the delegate executes every method in its collection, in the order they were added. A minor fact, because it would be bad code to have a delegate in which the execution order matters.

This type is useful for executing multiple standalone functions based on 1 specific event. For example, lets say that you have an event in your game: “Player Dies”. When the player dies, there are multiple things you want to do; make the player explode, change the music, fade the screen and save the game.

This is a case were multiple UNRELATED components need to react to the player dying. Were the player only to explode, you could simply call that method in the player himself. Were it only the music that needed to change, then perhaps the player could simply call the music player (pun not intended). But we are talking about several unrelated actions that need to be taken whenever this one event takes place. It would be impossible to keep track of our code doing this hardcoded, so it is always better to use delegates in this case.

Hope you learned something, but you really shouldn’t listen to me because I’m just mostly guessing about this stuff.

Privacy & Terms