MessageTypes with Parameter
It is often useful not only to inform Receivers that a Message of a certain type has been sent, but also to send data along with the Message. Receivers can then process this data upon reception of the Message.
Creating a MessageType with Parameter
Using the Editor
The recommended way is to create new MessageTypes via the context menu in the editor project view.
- in the project view: navigate to the folder where you want to create the new MessageType
- in the project view: right click inside the folder
- in the context menu: navigate to
Create > GlobalMessage > MessageType with Param
- name the new file according to your new MessageType name. This will create your MessageType with
int
as the default parameter type.
- to change the parameter type, open your MessageType's C# script file. Change the generic parameter inside the class declaration from
int
to your desired parameter type - the final declaration of your MessageType should read like this:
public class YourMessageType : MessageType<YourParamType>
From Code
- create a new class that derives from
MessageType<T>
- set the generic parameter type to your desired parameter type
Here is a complete example of a MessageType with bool
as its parameter type. EditorSettings
are optional but good practice.
using MalteHusung.GlobalMessage;
[MessageTypeEditorSettings(Description = "This is my new MessageType with bool as parameter.", UseEditorFeatures = true, UseEditorMessageObject = true)]
public class NewMessageType : MessageType<bool>
{
}
Supported Parameter Types for Full Editor Integration
GlobalMessage offers many tools to easily interact with the system via the Editor. Most of them work directly out of the box for every MessageType you create. However for Sending Messages via Editor and Sending Messages via Component, not all parameter types are supported. If you want to use these features, the parameter type has to follow the Unity Serialization Rules. The following types are supported:
- custom serializable
class
andstruct
enum
- numeric type has to be
int
(default) orbyte
. - Make sure your default value has the numeric value 0 assigned.
- numeric type has to be
int
float
bool
string
Vector2
Vector3
Quaternion
Note
If you want to use any other type that is serialized by Unity, you can wrap it in a custom serializable class or struct.
Renaming Parameter Types
Generally, it is recommended to avoid renaming the parameter type whenever possible as the serialized data of MessageSender
components can easily get corrupted if done wrong.
However, if renaming is really necessary, decorate your type declaration with the MovedFrom
attribute (UnityEngine.Scripting.APIUpdating.MovedFromAttribute) before you perform the renaming via your IDE's rename functionality. This way, all serialized data should stay valid.
Note
Info about renaming your MessageTypes
can be found here.