Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Unity Scripting

You're reading from   Mastering Unity Scripting Learn advanced C# tips and techniques to make professional-grade games with Unity

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher
ISBN-13 9781784390655
Length 380 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Alan Thorn Alan Thorn
Author Profile Icon Alan Thorn
Alan Thorn
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Unity C# Refresher FREE CHAPTER 2. Debugging 3. Singletons, Statics, GameObjects, and the World 4. Event-driven Programming 5. Cameras, Rendering, and Scenes 6. Working with Mono 7. Artificial Intelligence 8. Customizing the Unity Editor 9. Working with Textures, Models, and 2D 10. Source Control and Other Tips Index

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 UnityEngine;
02 using System.Collections;
03 
04 public class MyClass : MonoBehaviour 
05 {
06 void start()
07 {
08        //Will invoke MyFunction on ALL components/scripts attached to this object (where the function is present)

09         SendMessage("MyFunction", SendMessageOptions.DontRequireReceiver);

10 }
11 
12 //Runs when SendMessage is called
13 void MyFunction()
14 {
15        Debug.Log ("hello");
16 }
17 }

The following are the comments for code sample 1-16:

  • Line 09: SendMessage is called to invoke the function MyFunction. MyFunction will be invoked not only on this class but on all other components attached to GameObject, if they have a MyFunction member, including the Transform component as well as others.
  • Line 09: The parameter SendMessageOptions.DontRequireReceiver defines what happens if MyFunction is not present on a component. Here, it specifies that Unity should ignore the component and move on to the next calling MyFunction wherever it is found.

    Tip

    The term function and member function mean the same thing when the function belongs to a class. A function that belongs to a class is said to be a member function.

We've seen that SendMessage invokes a specified function across all components attached to a single GameObject. BroadcastMessage incorporates the SendMessage behavior and goes a stage further, that is, it invokes a specified function for all components on GameObject and then repeats this process recursively for all child objects in the scene hierarchy, cascading downwards to all children.

More information on SendMessage and BroadcastMessage can be found at http://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html and http://docs.unity3d.com/ScriptReference/Component.BroadcastMessage.html.

Note

Reflection

SendMessage and BroadcastMessage are effective ways to facilitate inter-object communication and inter-component communication, that is, it's a great way to make components talk to one another if they need to, to synchronize behavior and recycle functionality. However, both SendMessage and BroadcastMessage rely internally on a C# feature known as reflection. By invoking a function using a string, your application is required to look at itself at runtime (to reflect), searching its code for the intended function to run. This process is computationally expensive compared to running a function in the normal way. For this reason, seek to minimize the usage of SendMessage and BroadcastMessage, especially during Update events or other frame-based scenarios, as the impact on performance can be significant. This doesn't mean you should never use them. There might be times when their use is rare, infrequent, and convenient and has practically no appreciable impact. However, later chapters in this book will demonstrate alternative and faster techniques using delegates and interfaces.

If you'd like more information on C# and its usage before proceeding further with this book, then I recommend the following sources:


The following are a few online resources:

You have been reading a chapter from
Mastering Unity Scripting
Published in: Jan 2015
Publisher:
ISBN-13: 9781784390655
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime