Unity

Unity integration

The MessagingModule class contains various methods that are used for subscribing and unsubscribing to topics, sending messages to a particular user (for admin users only), and receiving messages from the messaging service.

Currently supported topics:

  1. RGN.Modules.Inventory.InventoryModule.ITEM_ADDED_EVENT_TOPIC - this event is triggered when a new virtual item is added to the user's inventory by using the RGN.Modules.Inventory.InventoryModule.AddToInventoryAsync method.

  2. RGN.Modules.Inventory.InventoryModule.ITEM_REMOVED_EVENT_TOPIC - this event is triggered when an inventory item is removed by using the RGN.Modules.Inventory.InventoryModule.RemoveByInventoryItemIdAsync method.

Subscribe and Unsubscribe

The Subscribe method is used to subscribe the message receiver to a particular topic:

void Subscribe(string topic, IMessageReceiver messageReceiver)

IMessageReceiver interface is intended to be implemented by classes that want to receive and handle messages. The IMessageReceiver interface defines a single method named OnMessageReceived, which takes two parameters - a string named topic and an object of the type Message.

The topic parameter is used to identify the specific topic or channel that the message was sent on and the message parameter contains the actual message data.

The Unsubscribe method is used to unsubscribe the message receiver from a particular topic.

Here is a code example:

using UnityEngine;
using RGN.Modules.Messaging;

public class MessagingExamples : MonoBehaviour, IMessageReceiver
{
    private void Start()
    {
        // TODO: use module constants for topic parameter, for example:
        // RGN.Modules.Inventory.InventoryModule.ITEM_ADDED_EVENT_TOPIC
        MessagingModule.I.Subscribe("it_is_better_to_use_module_constants", this);
    }

    private void OnDestroy()
    {
        MessagingModule.I.Unsubscribe("it_is_better_to_use_module_constants", this);
    }

    public void OnMessageReceived(string topic, Message message)
    {
        Debug.Log($"New message received for topic : {topic}, message : {message}");
    }
}

The sample above shows an implementation of the IMessageReceiver interface in a class called SomeNotificationReceiver. This class inherits from MonoBehaviour, which is a Unity class that allows for the creation of scripts that can be attached to game objects in a Unity scene.

The SomeNotificationReceiver class subscribes to a specific message topic by calling the MessagingModule.I.Subscribe method and passing in the topic string and an instance of itself as the message receiver. It also unsubscribes from the same topic in its OnDestroy method by calling the MessagingModule.I.Unsubscribe method.

The OnMessageReceived method simply logs a message to the Unity console with the topic and message received. You can implement your own message handling code.