Game Development Reference
In-Depth Information
using UnityEngine;
public class MessagingClientBroadcast : MonoBehaviour {
void OnCollisionEnter2D(Collision2D col)
{
MessagingManager.Instance.Broadcast();
}
}
The preceding code is just a simple example so that when attached to an object with a 2D
collider, it will trigger a broadcast. To test, just add it to one or both of the border objects
in our game scene. In this way, if the player tries to leave the scene, it will ring the alarm
bells.
At the moment though, no one is listening, so let's add a listener/receiver. Create another
C# script and name it
MessagingClientReceiver
. This script will register for
events and log in to the
Console
window with some information about the object it's at-
tached to (obviously, there will be no information from the broadcast event as it has
none); the following code will tell you how to do this:
using UnityEngine;
public class MessagingClientReceiver : MonoBehaviour
{
void Start()
{
MessagingManager.Instance.Subscribe(ThePlayerIsTryingToLeave);
}
void ThePlayerIsTryingToLeave()
{
Debug.Log("Oi Don't Leave me!! - " + tag.ToString());
}
}
In simple words, when the game object script is attached to a startup, it will register itself
with the
MessagingManager
script, telling the
manager
class to run the second