Hi, looking through the Unity docs I noticed the BroadcastMessage and SendMessage methods. I’m assuming this is Unity’s version of C sharp delegates and events? Are there any advantages of using one over the other in terms of performance or usage?
SendMessage and delegates are used for similar purposes, but they work entirely differently. Delegates/Events behave exactly like they do in any other .Net program. SendMessage() is called much like Unity calls other messages like Update(). Unity reflects over all the code on the game object to see if it can invoke any messages.
As far as performance. Delegates are several times faster than SendMessage. In the order of performance:
As far as usage, SendMessage is like a very broad direct method call. The general paradigm is that one script specifically wants to send a message to a specific object. We’re just not sure how many times is can respond or if it can respond at all. We know the intended receiver, we just don’t know if it can receive the message.
With events, I usually follow the idea that the event owner doesn’t know who or how many objects might respond. We are simply telling the world that something happened without too much knowledge of who will use this information.
@Beugenen, the possibility of a memory leak comes from listeners preventing garbage collection. While conceptually “Emitters don’t know or care who’s listening” they actually do have a direct reference to each listener, this is why they are fast. But this means that listing object won’t get garbage collected until either the listener is removed, or the emitter is destroyed. If the listener is some persistent object like a player or worse level loader, then you open the door for a memory leak
Well I want to put a new paradigm to this question . Unity now has its own event system is this better performance wise as compared to C sharp events and delegates