Course contentsShow
← Unity Game Development
Lesson 86 of 8282. Scripting and LifecycleFree lesson

Sending Messages with SendMessage and BroadcastMessage

Explore the use of SendMessage to trigger methods on objects dynamically, understanding both the convenience and the architectural trade-offs involved.

In this lesson, you will learn how to trigger methods on GameObjects without needing a direct reference to their specific script components.

What are Messaging Methods?

Usually, to call a function on another script, you use GetComponent<T>() to get a reference and then call the method. However, Unity provides a "loose coupling" alternative: SendMessage. This allows you to "shout" a method name as a string into an object, and if that object has a public or private method with that exact name, Unity will execute it.

SendMessage vs. BroadcastMessage

  • SendMessage("MethodName"): This only searches the target GameObject. If the object has three different scripts attached and one of them contains void MethodName(), that method will run.
  • BroadcastMessage("MethodName"): This is more aggressive. It triggers the method on the target GameObject and every single child object in its hierarchy.

A Quick Example

Imagine you have a "Trap" object. When a player touches it, you want to trigger a ResetTrap() function on any script attached to that object.

void OnTriggerEnter(Collider other)
{
    // Simply fire the message without needing to know the specific script type
    gameObject.SendMessage("ResetTrap", SendMessageOptions.DontRequireReceiver);
}

By adding SendMessageOptions.DontRequireReceiver, you prevent Unity from throwing an error in the console if the object happens to be missing that specific method.

Architectural Trade-offs

While this seems convenient, it comes with a cost:

  1. Performance: Because these methods rely on "reflection" (Unity searching through scripts by name at runtime), they are significantly slower than direct method calls or interface implementations.
  2. Safety: Because you are calling methods using strings, the compiler won't warn you if you have a typo. If you change a method name in your script but forget to update the string in your SendMessage call, your code will fail silently without a warning.

Use these methods for quick prototypes or very loose, non-critical event systems, but rely on direct references for core game logic to keep your code fast and maintainable.

Key Takeaway: SendMessage and BroadcastMessage provide a way to trigger logic without direct references, but they trade type-safety and performance for convenience.