Get started with CloudBehaviours
Deploy your first CloudBehaviour, then confirm your game can call it and receive updates.
Read time 10 minutesLast updated 2 days ago
Create a CloudBehaviour that keeps a counter for each player, connect your game to it, and call it from a script. When you finish, your game signs a player in, calls the CloudBehaviour, and receives the updated counter from the cloud.
This walkthrough uses a -scoped CloudBehaviour, which holds state for one signed-in player. For a CloudBehaviour that every player in a multiplayer session shares, refer to Turn-based game workflow. For an explanation of the component that connects your game to a CloudBehaviour, refer to Client bindings in CloudBehaviours.
PlayerPrerequisites
Before you start, confirm that your project meets the following prerequisites:
- Your project uses Unity 6.7 or later.
- Cloud Code is set up in the Unity Editor. Follow the steps in Set up the Unity Editor to link your project to Unity Gaming Services (UGS), install the required packages and .NET, and set up the Deployment window.
- The experimental version of the Cloud Code package () that includes CloudBehaviours is installed. Follow the steps in Install a UPM package by name, with
com.unity.services.cloudcodeas the name andcom.unity.services.cloudcodeas the version. Enter the version explicitly, because Package Manager otherwise installs the latest released version, which doesn't include CloudBehaviours.3.1.0-exp.1 - The ASP.NET Core Runtime 10.0 (Microsoft) is installed, so you can run your CloudBehaviour on a local Cloud Code server. The .NET Runtime download alone isn't enough to start the local server.
- If you use a -scoped CloudBehaviour, the Multiplayer Services package (
MultiplayerSession) is installed. Thecom.unity.services.multiplayer-scoped example on this page doesn't need the Multiplayer Services package.Player
To confirm that your installed package version includes CloudBehaviours, check that the Create > Services > Cloud Behaviour Script menu item exists. If the menu item doesn't exist, your installed version doesn't include CloudBehaviours.
Learn the CloudBehaviour workflow
A CloudBehaviour has two parts. The cloud script is a C# class that derives from and runs in Cloud Code, either on a local Cloud Code server or on the Cloud Code service. The client bindings are a component that the Editor generates from the cloud script. Your game uses the client bindings to call the cloud script and receive its state.
CloudBehaviourBuilding a CloudBehaviour involves the following stages:
- Write the cloud script. Each public member of the class becomes a feature of the client bindings.
- Add the generated client bindings component to a GameObject in the scene.
- Sign the player in, so the client bindings component can connect to the player's CloudBehaviour.
- Call RPCs, read synchronized state, and listen for push channel events from the game.
- Run the CloudBehaviour on a local Cloud Code server, then deploy it to the Cloud Code service.
The workflow uses the following parts of the Unity Editor:
- The Create > Services > Cloud Behaviour Script menu item, which creates the cloud script and the client bindings script.
- The client bindings component in the Inspector window, which shows the connection status and the synchronized state.
- The Cloud Code toolbar button, which starts and stops the local Cloud Code server.
- The Deployment window, which deploys the module to the Cloud Code service.
This walkthrough uses RPCs, synchronized state, and a push channel. CloudBehaviours also support timers, per-player state views, access control, and calls between CloudBehaviours.
Create a CloudBehaviour
To create a CloudBehaviour script:
- In the Project window, select or create a folder to contain your CloudBehaviour.
- Right-click the folder, then select Create > Services > Cloud Behaviour Script.
- Name the script .
MyCloudBehaviour - In the Cloud Behaviour Module Creator window, enter as the module name, then select Confirm.
MyModule
The Editor creates a folder that contains the following items:
MyModule- A folder with the
Cloudassembly, which holds your cloud script,MyModule.MyCloudBehaviour.cs - A folder with the
Clientassembly, which holds your client bindings script,MyModuleClient.MyCloudBehaviourClient.cs - A file. The module appears in the Deployment window as a Cloud Code module.
MyModule.ccmu
The generated cloud script contains the following class. The generated file also contains a namespace and explanatory comments, which this example omits.
using System;using Microsoft.Extensions.Logging;using Unity.Services.CloudBehaviours;using Unity.Services.CloudCode.Core;[StateScope(Scope.Player)]public class MyCloudBehaviour : CloudBehaviour{ public int Counter = 0; public event Action<string> OnSayHello; public string SayHello(string name) { Counter++; Logger.LogDebug($"Counter: {Counter}"); OnSayHello?.Invoke(name); return $"Hello, {name}!"; }}
The following table describes how each public member of the class is exposed.
Member | Member type | Feature | Description |
|---|---|---|---|
| Public field | Synchronized state | Cloud Code stores the value for each player, and your game receives the current value. |
| Public event | Push channel | Cloud Code notifies your game when |
| Public method | Remote procedure call (RPC) | Your game can call the method remotely. |
You don't need to change the generated cloud script for this walkthrough. The Editor regenerates the client bindings automatically each time the cloud script compiles.
Add the client bindings to your scene
The client bindings script is a component that connects your game to the CloudBehaviour.
To add the client bindings component to your scene:
- In the Hierarchy window, right-click and select Create Empty.
- Rename the new GameObject to .
CloudBehaviour - In the Inspector window, select Add Component, then search for and select My Cloud Behaviour Client.
The GameObject now has the My Cloud Behaviour Client component. The component connects to your CloudBehaviour after a player signs in, which you set up in the next section.
CloudBehaviourIf My Cloud Behaviour Client isn't in the list, check the Console window for a error on your cloud script. The Editor doesn't generate client bindings until you fix the error. In version 3.1.0-exp.1, a project that includes the Netcode for Entities package reports and errors instead, and the Editor doesn't generate client bindings until you remove that package.
CCSGCCSG902CCSG908Sign the player in
A -scoped CloudBehaviour needs a signed-in player. The client bindings component connects automatically after the player signs in.
PlayerTo sign the player in when your game starts:
-
In the Project window, right-click a folder outside thefolder, such as
MyModule, then select Create > MonoBehaviour Script. The client assembly doesn't reference the Authentication package, so a script inside theAssetsfolder can't sign the player in.Client -
Name the script.
SignIn -
Double-clickto open it in your configured external script editor.
SignIn.cs -
Replace the contents of the script with the following code, which initializes Unity Gaming Services and signs the player in anonymously:using Unity.Services.Authentication;using Unity.Services.Core;using UnityEngine;public class SignIn : MonoBehaviour{ async void Start() { await UnityServices.InitializeAsync(); if (!AuthenticationService.Instance.IsSignedIn) await AuthenticationService.Instance.SignInAnonymouslyAsync(); Debug.Log($"Signed in as player {AuthenticationService.Instance.PlayerId}."); }}
-
In the Hierarchy window, select theGameObject.
CloudBehaviour -
In the Inspector window, select Add Component, then search for and select Sign In.
When your game starts, the Sign In component signs the player in, and the client bindings component connects to the player's CloudBehaviour.
Call the CloudBehaviour
After the player signs in, the client bindings component connects to the player's CloudBehaviour and raises the event. Call RPCs from a handler or from player input, rather than immediately after , because the client bindings component isn't connected yet at that point.
ScopeChangedScopeChangedEnableClient()To call the CloudBehaviour when the client bindings component connects:
-
In the Project window, open thefolder, then double-click
MyModule/Clientto open it in your external script editor.MyCloudBehaviourClient.cs -
Replace theclass with the following class. Keep the
MyCloudBehaviourClientdirectives and the namespace that the Editor generated. The class callsusingwhen the client bindings component connects, reads the updatedSayHellovalue, and logs eachCounterpush channel event:OnSayHello[CloudBehaviour(typeof(MyCloudBehaviour))]public partial class MyCloudBehaviourClient : MonoBehaviour{ protected virtual void OnEnable() { ScopeChanged.AddListener(OnScopeChanged); OnSayHello.AddListener(OnHelloReceived); EnableClient(); } protected virtual void OnDisable() { DisableClient(); ScopeChanged.RemoveListener(OnScopeChanged); OnSayHello.RemoveListener(OnHelloReceived); } async void OnScopeChanged() { // The scope is null when the player signs out. if (Scope == null) return; var greeting = await SayHello("World"); Debug.Log($"{greeting} Counter is now {Counter}."); } void OnHelloReceived(string name) { Debug.Log($"Received the OnSayHello event for {name}."); }}
Your client bindings script now calls each time the client bindings component connects. To test the script, run your CloudBehaviour on the local server.
SayHelloRun your CloudBehaviour on the local server
Run your CloudBehaviour on a local Cloud Code server to iterate quickly. The local server supports breakpoints, so you can debug your cloud logic like any other script.
To run your CloudBehaviour on the local server:
- Enable the Cloud Code toolbar button. Follow the steps in Enable the Cloud Code toolbar button.
- Select the Cloud Code toolbar button, then select Start Local Server. The local server compiles and deploys every Cloud Code module in your project, including .
MyModule - Enter Play mode.
After you enter Play mode, the Console window shows the following messages:
Signed in as player <player ID>.Hello, World! Counter is now 1.Received the OnSayHello event for World.
The push channel event and the RPC response arrive separately, so the message might appear before the message.
OnSayHelloHello, World!In the Inspector window, the client bindings component shows its connection status and the current value of . Each time you enter Play mode, increases by one, because Cloud Code stores -scoped state between sessions. To reset , follow the steps in Reset local state.
CounterCounterPlayerCounterIf the Console window shows a error with the message , the local server wasn't running when you entered Play mode. Exit Play mode, start the local server, then enter Play mode again.
HydrationFailedOnConnectModule could not be foundRun your CloudBehaviour on the Cloud Code service
While the local Cloud Code server runs, the Deployment window deploys your modules to the local server instead of to the Cloud Code service.
To run your CloudBehaviour on the Cloud Code service:
- If the Editor is in Play mode, exit Play mode. The Editor chooses between the local server and the Cloud Code service when you enter Play mode, so your game keeps calling the local server until you exit Play mode.
- Select the Cloud Code toolbar button, then select Stop Local Server.
- Select Services > Deployment to open the Deployment window.
- In the Deployment window, select , then select Deploy Selected. The Deployment window deploys the module to the environment that's selected in the window.
MyModule.ccmu - Enter Play mode.
Your game connects to the CloudBehaviour on the Cloud Code service, and the Console window shows the same messages as on the local server. The value in the Cloud Code service is separate from the value on the local server, so it starts again at .
Counter1Get the player ID
A player ID identifies a signed-in player. The following table lists how to get the player ID, depending on where your code runs.
Where your code runs | How to get the player ID |
|---|---|
| Game client, after sign-in completes | |
| Cloud script, in an RPC that a player calls | |
| Cloud script, for every player in a multiplayer session | |
| Cloud script, in a call from a timer or another service | |
For a -scoped CloudBehaviour, the client bindings component follows the signed-in player by default. To follow one specific player, pass the player ID to after sign-in completes:
PlayerEnableClientawait AuthenticationService.Instance.SignInAnonymouslyAsync();EnableClient(AuthenticationService.Instance.PlayerId);