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 containsvoid 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:
- 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.
- 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
SendMessagecall, 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.