x


Send/Broadcast message vs Delegates and Events

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?

Many thanks!

more ▼

asked Nov 14 '11 at 09:19 PM

AntLewis gravatar image

AntLewis
315 41 55 66

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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:

 (Least) Direct Method Call ==> Delegate/Event ==> Update() ==> SendMessage (Most Expensive)

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.

more ▼

answered Nov 14 '11 at 11:04 PM

Peter G gravatar image

Peter G
15k 16 44 136

Many thanks for the thorough response, much appreciated.

Nov 18 '11 at 05:34 PM AntLewis

Also helped me. Thanks.

Dec 23 '12 at 09:34 PM GeorgeRigato

Agreed. One thing con of events is that one must subscribe to them and remember to unsubscribe later via "-=" else it can lead to a memory leak. As opposed to SendMessage which is loosely coupled

Mar 30 at 02:20 AM Beugnen
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x47
x31

asked: Nov 14 '11 at 09:19 PM

Seen: 3029 times

Last Updated: Mar 30 at 02:20 AM