SendMessage and BroadcastMessage

The MonoBehaviour class included in the Unity API, which acts as the base class for most new scripts, offers the SendMessage and BroadcastMessage methods. Using these, you can easily execute functions by name on all components attached to an object. To invoke a method of a class, you typically need a local reference to that class to access and run its functions as well as to access its variables. However, the SendMessage and BroadcastMessage functions let you run functions using string values by simply specifying the name of a function to run. This is very convenient and makes your code look a lot simpler and shorter at the cost of efficiency, as we'll see later. Refer to the following code sample 1-16:

01 using ...

Get Mastering Unity Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.