Why You May Want To Use A Delegate

In response to that other question which I thought was a pretty fair question I started thinking about why you would use a Delegate over simply creating an Event that fires all the logic and here is what I came up with:

Decoupling: Say you need actors to take damage from the Weather System. You could get all actors of class and filter out a specific player class and then do a foreach loop on them and fire their individual functions…or you could simply create a Delegate on the Weather system that you can have that class bind too.

This also avoids Hard References and Dependency Chains if careful because by referencing something Permanent in the game from a Spawn Actor you avoid Directly referencing those actors. Dependency Chains is caused by Hard References, Hard References are addresses to things already loaded into memory. This means when you place a hard reference in say an Inventory System to a Blueprint with a dozen references to other things, and you have 500 inventory items…you may be forcing the engine to load 50,000 other items into memory. A lot of people discount this but it adds up quick and significantly slows down loading times

Binding and Unbinding: This goes back to Decoupling and it allows you to dynamically bind things to events. In some cases maybe you want functionality to happen during an event over a period of time but then after so long you want that functionality to stop, you can simply Unbind from that event. That part may not seem noteworthy but the ability to Bind and Unbind dynamically during run-time is pretty useful. (This may be needed in such a case that for example you want to give the player Temporary Immunity to the Damage caused by the Weather System, you could Unbind and then Bind back to it when your done)

You’ll find yourself using Dynamic Delegates (Event Dispatchers in Blueprints) when dealing with systems that you want to extend or be portable in some way.

Ultra Dynamic Sky has Delegates you can bind to for handling functionality outside of their Weather and Day/Night System when specific Weather and Time Cycle Events happen. If we didn’t have delegates you would have to open it up and manually grab hard references for everything and fire their specific events or use an Interface on them to avoid the hard reference.

So I guess you could technically get away without Hard References in some cases by using Interfaces but you would still need some way to actively grab the actors you need to fire functions on because Interfaces still need to be fired on the actor that has the interface and I do believe there is a way to get all actors with a specific interface but this would be dramatically more expensive I would think then simply binding to Dynamic Delegates.

P.S. Unreal Source Code makes use of Delegates too, they aren’t all that bad as long as you use them responsibly.

Privacy & Terms