How To: Use Pixel Crushers Message System
Posted: Wed Nov 25, 2020 11:07 am
This post describes how to use the Pixel Crushers Message System, which is a general-purpose message system that's heavily used by Quest Machine and can also be used by the Dialogue System.
Messages have three parts:
To make a script listen for messages, implement the C# interface IMessageHandler and register to listen for specific types of messages. Example:
---
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.
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.