Messages have three parts:
- The message (a string or StringField)
- An optional parameter (a string or StringField) [EDIT: parameter required, but it can be a blank string]
- Zero or more optional values of any type.
- Message: "Entered"
- Parameter: "Jungle"
- (No extra values)
Code: Select all
// Send Entered + Jungle from 'this' (the class/object that is running this code):
PixelCrushers.MessageSystem.SendMessage(this, "Entered", "Jungle");
Code: Select all
public class EntranceAlerter : MonoBehaviour, IMessageHandler
{
void OnEnable()
{
// Listen for any "Entered" + "(whatever)" messages:
PixelCrushers.MessageSystem.AddListener(this, "Entered", string.Empty); // Empty string means any parameter.
}
void OnDisable()
{
PixelCrushers.MessageSystem.RemoveListener(this);
}
void OnMessage(MessageArgs messageArgs)
{
if (messageArgs.message == "Entered")
{
if (messageArgs.parameter == "Jungle")
{
DialogueManager.ShowAlert("Welcome to the jungle, we got fun and games!");
PlayMusic("GnR");
}
else
{
DialogueManager.ShowAlert("Entered some boring area named " + messageArgs.parameter);
}
}
}
}
Sender and target:
Messages are always sent from a sender. The sender is specified in the first parameter to MessageSystem.SendMessage.
You can also address a message to a specific target by using MessageSystem.SendMessageWithTarget. The message will still be sent to all listeners, but messageArgs.target will be set to the target. The target listener (or any listener interested in messages to the target) can check messageArgs.target.