Send push messages
Push messages to clients over a WebSocket connection from Cloud Code modules.
Read time 7 minutesLast updated 18 hours ago
Cloud Code C# modules allow you to push messages to clients over a WebSocket. This page provides an overview of this feature and instructions on how to use it in Cloud Code modules and the Cloud Code SDK.
To send push messages, you need to call a module endpoint. You can subscribe to push messages from the Unity Editor.
Use cases and benefits
You can use push messages for a variety of purposes, such as the following:Use | Example | Benefit |
|---|---|---|
| Push messages from the server to clients in real time and enhance interactivity for your games. | You can notify players about game events, updates, or asynchronous multiplayer games (for example, competitive card games). | Real-time interaction |
| Keep users up-to-date with the latest events, changes, or actions in the game by pushing updates and notifications directly to the client. | You can notify your users as soon as new data is available so you don't need to manually refresh or check for updates. This can be especially useful for games that require frequent updates, such as real-time strategy games. | User experience |
| Use WebSockets to push messages for more efficiency than traditional polling techniques. | Your client can wait for the server to send new data when it becomes available instead of continuously asking the server for new data. This reduces unnecessary network traffic and can lead to lower latency. | Efficient network usage |
| Use the scalability of the push model to support games with a large number of users. | You can use push messages in Cloud Code to send updates to all connected clients at once, and reduce the operating cost and amount of requests for multiplayer games with a large number of players. | Scalability and cost |
| Customize your game's response to different types of messages with the event-driven model. | You can trigger different game actions based on the MessageType property of the messages you receive. | Customizability |
| As part of the Unity ecosystem, use Cloud Code is seamlessly with other Unity services. | You can handle player authentication with Unity's Authentication service, and process the messages within the Unity game engine. | Seamless integration |
Create a module
The following code example demonstrates the basic structure for a module that includes two methods:- : sends a message to a specific connected player.
SendPlayerMessage - : broadcasts a message to all connected players in the project.
SendProjectMessage
The
Unity.Services.CloudCode.ApisPushClientTo learn how to deploy a module, refer to the Deploying Hello World page.using Microsoft.Extensions.DependencyInjection;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Apis;namespace PushExample{ public class PushExample { [CloudCodeFunction("SendPlayerMessage")] public async Task<string> SendPlayerMessage(IExecutionContext context, PushClient pushClient, string message, string messageType, string playerId) { var response = await pushClient.SendPlayerMessageAsync(context, message, messageType, playerId); return "Player message sent"; } // Recommended to use access control to limit access to this endpoint [CloudCodeFunction("SendProjectMessage")] public async Task<string> SendProjectMessage(IExecutionContext context, PushClient pushClient, string message, string messageType) { var response = await pushClient.SendProjectMessageAsync(context, message, messageType); return "Project message sent"; } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(PushClient.Create()); } }}
Set up the Unity Editor
The Cloud Code SDK provides an interface for subscribing to messages. You can subscribe to messages for a specific player or for the entire project. To use Cloud Code in the Unity Editor, you must first install the Cloud Code SDK and link your Unity Gaming Services project to the Unity Editor.Link project
Link your Unity Gaming Services project with the Unity Editor. You can find your UGS project ID in the Unity Dashboard.- In Unity Editor, select Edit > Project Settings > Services.
-
Link your project.
If your project doesn't have a Unity project ID:- Select Create a Unity Project ID > Organizations, then select an organization from the dropdown.
- Select Create project ID.
If you have an existing Unity project ID:- Select Use an existing Unity project ID.
- Select an organization and a project from the dropdowns.
- Select Link project ID.
UnityEditor.CloudProjectSettings.projectIdSDK installation
Install the latest Cloud Code package for Unity Editor:- In the Unity Editor, open Window > Package Manager.
- In the Package Manager, select the Unity Registry list view.
- Search for , or locate the Cloud Code package in the list.
com.unity.services.cloudcode - Select the package, then click Install.
SDK setup
Get started with the Cloud Code SDK:- Ensure the service is enabled via the Cloud Code service dashboard page.
- Ensure that you have installed both the Cloud Code and the Authentication SDKs.
- Sign into your cloud project from within Unity Editor by selecting Edit > Project Settings > Services.
- Create a new C# Monobehaviour script in Unity Editor. Refer to Creating and using scripts in the Unity Manual.
- In the script, initialize the Core SDK using await .
UnityServices.InitializeAsync() - In the script, initialize the Authentication SDK.
await AuthenticationService.Instance.SignInAnonymouslyAsync();
Subscribe to messages
You can subscribe to messages for a specific player or for the entire project. You can use the following code snippet as a guide for aMonoBehaviourusing System;using System.Threading.Tasks;using Newtonsoft.Json;using Unity.Services.Authentication;using Unity.Services.CloudCode;using Unity.Services.CloudCode.Subscriptions;using Unity.Services.Core;using UnityEngine;namespace CloudCode{ public class CloudCodePushExample : MonoBehaviour { async void Start() { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignInAnonymouslyAsync(); Debug.Log(AuthenticationService.Instance.PlayerId); await SubscribeToPlayerMessages(); await SubscribeToProjectMessages(); } // This method creates a subscription to player messages and logs out the messages received, // the state changes of the connection, when the player is kicked and when an error occurs. Task SubscribeToPlayerMessages() { // Register callbacks, which are triggered when a player message is received var callbacks = new SubscriptionEventCallbacks(); callbacks.MessageReceived += @event => { Debug.Log(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")); Debug.Log($"Got player subscription Message: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.ConnectionStateChanged += @event => { Debug.Log($"Got player subscription ConnectionStateChanged: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.Kicked += () => { Debug.Log($"Got player subscription Kicked"); }; callbacks.Error += @event => { Debug.Log($"Got player subscription Error: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; return CloudCodeService.Instance.SubscribeToPlayerMessagesAsync(callbacks); } // This method creates a subscription to project messages and logs out the messages received, // the state changes of the connection, when the player is kicked and when an error occurs. Task SubscribeToProjectMessages() { var callbacks = new SubscriptionEventCallbacks(); callbacks.MessageReceived += @event => { Debug.Log(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")); Debug.Log($"Got project subscription Message: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.ConnectionStateChanged += @event => { Debug.Log($"Got project subscription ConnectionStateChanged: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; callbacks.Kicked += () => { Debug.Log($"Got project subscription Kicked"); }; callbacks.Error += @event => { Debug.Log($"Got project subscription Error: {JsonConvert.SerializeObject(@event, Formatting.Indented)}"); }; return CloudCodeService.Instance.SubscribeToProjectMessagesAsync(callbacks); } }}
Send messages to players
To send messages to players, call either theSendPlayerMessageSendProjectMessageRun from Unity runtime
You can send messages to other players via theCallModuleEndpointAsyncCloudCodeServicevar sendPlayerMessageResult = await CloudCodeService.Instance.CallModuleEndpointAsync<string>("PushExample", "SendPlayerMessage",new Dictionary<string, object> {{"message", "hello with a player message from PushExample!"}, {"messageType", "testType"}, {"playerId", "<other-unity-player-ID>"}});
Events
Both player-specific and project-specific subscriptions have four event handlers:- : triggers when the player receives a new message.
MessageReceived - : triggers when the state of the connection changes.
ConnectionStateChanged - : triggers when the server forcefully unsubscribes the player from messages. This doesn't close the WebSocket connection, nor does it prevent the game client from subscribing to messages again.
Kicked - : triggers when an error occurs in handling the connection or when the player receives messages.
Error
Message envelope
TheIMessageReceivedEventIMessageReceivedEventProperty | Description | Example |
|---|---|---|
| The specification version of the received message's envelope. Use this property to ensure the client can process the message correctly. | 1.0 |
| A unique identifier for the message. Use this property to track or log messages. | |
| The source of the message's envelope. This indicates where the message originated from, which you can use to debug or route messages. The source is always the domain of Cloud Code. | |
| The message's envelope type. This property indicates the type of data the message contains and helps the client decide how to process it. The value is always a Cloud Code message type. | |
| The date and time of the message creation. You can use this property to log the messages, or to calculate latency. | |
| The ID of the project the message is associated with. | |
| The ID of the environment that the message is for. You can use this property to differentiate between different environments such as development, staging, and production. | |
| An identifier that you can use to track a sequence of related messages. For instance, if multiple messages form a conversation or workflow, they might share a correlation ID. | |
| The actual message content sent from Cloud Code to the player. | "hello world!" |
| The type of the message that the player receives. This is similar to | "Information" |