Documentation

Cloud Code

Open Unity Dashboard

Cloud Code

Cross-behaviour calls in CloudBehaviours

Call an endpoint on another CloudBehaviour from inside your own, in another scope instance or another module.
Read time 7 minutesLast updated 2 days ago

Important
This page describes an experimental feature that might change significantly before release. It's not recommended to use or rely on experimental features in production environments due to potential instability.
From inside a CloudBehaviour, you can call an endpoint on another CloudBehaviour. How you make the call depends on where the target runs:

Target

How to call it

A CloudBehaviour in another scope instance, in the same moduleUse the generated interface and
ForScopeAsync
. Refer to Call a CloudBehaviour in another scope instance.
A CloudBehaviour in another scope instance, in another moduleCall it as a Cloud Code module endpoint. Refer to Call a CloudBehaviour in another module.
The same CloudBehaviour in the current scope instanceCall the method directly, the same as any other C# method.
A different CloudBehaviour in the current scope instanceYou can't call it and wait for its result. Refer to Call the current scope instance.
A scope instance that's earlier in the current chain of callsYou can't call back into that scope instance with
ForScopeAsync
. Refer to Avoid calls back into an earlier scope instance.
To run an endpoint on the same CloudBehaviour later instead of now, schedule a timer. Refer to Timers in CloudBehaviours.

Call a CloudBehaviour in another scope instance

The Unity Editor generates an
I{Behaviour}
interface for every CloudBehaviour in your module. Inject the interface with
[CloudCodeService]
, then call a member on the interface to get back an
ICall
that hasn't run yet. To run the
ICall
, pass the target's scope ID to
ForScopeAsync(scopeId)
.
An
ICall
does nothing until you run it. If you create an
ICall
and never call
ForScopeAsync
or
ScheduleAsync
on it, the build fails.
The following example shows a
MultiplayerSession
-scoped
MatchRoom
that updates each player's
PlayerRecord
at the end of a match.
PlayerRecord
is
Player
-scoped because it belongs to one player and outlives any single match:
[StateScope(Scope.Player)]public class PlayerRecord : CloudBehaviour{ public int MatchesPlayed; public int PersonalBest; [CloudCodeAccess(Access.Service)] public int RecordMatch(int score) { MatchesPlayed++; if (score > PersonalBest) PersonalBest = score; return PersonalBest; }}[StateScope(Scope.MultiplayerSession)]public class MatchRoom : CloudBehaviour{ [CloudCodeSerializeProperty] private Dictionary<string, int> _scores = new(); public async Task EndMatch([CloudCodeService] IPlayerRecord playerRecord) { foreach (var entry in _scores) { var best = await playerRecord.RecordMatch(entry.Value).ForScopeAsync(entry.Key); Logger.LogInformation("{PlayerId} personal best is now {Best}", entry.Key, best); } }}
ForScopeAsync
takes the scope ID of the target CloudBehaviour's own
[StateScope]
, not the caller's scope ID. In this example,
entry.Key
is a player ID, which matches the
Scope.Player
scope of
PlayerRecord
.
ForScopeAsync
can't target the scope instance that's already running your code. If you pass
Context.ScopeId
, the build fails, because a scope instance can't start a second call while it's still running the current one. Refer to Call the current scope instance.
Awaiting the call returns the endpoint's return value directly. The caller doesn't receive the target's synchronized state. If the call changes that state, Cloud Code pushes the new state to the clients in the target's scope, the same as after any other endpoint call, unless the target has turned off
AutoSynchronize
. In this example, each player receives their updated
PlayerRecord
. For more information, refer to Control synchronization manually.

Get a scope ID

Read the scope ID to pass to
ForScopeAsync
from the CloudBehaviour's
Context
:

Target scope

Scope ID

Notes

Scope.Player
Context.PlayerId
The ID of the player making the current call. For the other players in a session, use
Context.Session.PlayerIds
.
Scope.MultiplayerSession
Context.Session.Id
Only available when the calling CloudBehaviour is
MultiplayerSession
-scoped.
Context.Session
is
null
otherwise.
When another CloudBehaviour calls the endpoint,
Context.PlayerId
doesn't contain a player ID, because the call uses the calling CloudBehaviour's service token. In a
Player
-scoped CloudBehaviour, read the owner's player ID from
Context.ScopeId
instead.

Restrict access to the target endpoint

A cross-behaviour call arrives with no player identity. The player ID you pass to
ForScopeAsync
selects only which scope instance runs the endpoint. The player ID doesn't make the call on that player's behalf.
The target is still an endpoint that a client can call directly. Mark the target
[CloudCodeAccess(Access.Service)]
so no player can call it directly. Refer to Access control in CloudBehaviours.

Call a CloudBehaviour in another module

The generated interface only reaches CloudBehaviours in the same module. To call a CloudBehaviour in another module, call its endpoint as a Cloud Code module endpoint, and pass the scope ID of the target scope instance. The target scope instance must be different from the one that's running your code. Refer to Call the current scope instance.

Call the current scope instance

Scope instances are non-reentrant, which means that each scope instance runs one call at a time. While your endpoint runs, other calls to the same scope instance wait until your endpoint finishes. If your endpoint calls into its own scope instance, that call fails. The type of failure depends on how you make the call:
  • If you call through the generated interface with
    ForScopeAsync
    , the call fails immediately. If you pass
    Context.ScopeId
    , the build fails. If you pass another value that matches the current scope ID, the call throws an
    InvalidOperationException
    at runtime.
  • If you call a Cloud Code module endpoint, including a CloudBehaviour in another module, nothing stops the call. The call waits for your endpoint, and your endpoint waits for the call, until the request fails with a
    Gateway Timeout
    error.
To run code on the same CloudBehaviour in the current scope instance, call the method directly, the same as any other C# method. You can't call a different CloudBehaviour in the current scope instance and wait for its result.
To share logic between modules in the same scope, refer to Avoid calls into your own scope.

Avoid calls back into an earlier scope instance

Because scope instances are non-reentrant, a call back into an earlier scope instance can't run. Consider two scope instances,
s1
and
s2
. An endpoint in
s1
calls an endpoint in
s2
and waits for the result. If the endpoint in
s2
then calls back into
s1
,
s1
can't run the call from
s2
until the endpoint in
s1
finishes, and the endpoint in
s1
is waiting for
s2
. Neither endpoint could finish, because each would wait for the other. This situation is a deadlock.
To prevent the deadlock, a
ForScopeAsync
call into a scope instance that's earlier in the current chain of calls, such as
s1
, fails immediately with an
InvalidOperationException
. The exception message starts with
ForScopeAsync cycle
. The call fails even if the endpoint in
s1
doesn't await its call to
s2
.
In the following example, the
Begin
endpoint runs in session
s1
and awaits the
Forward
endpoint in session
s2
.
Forward
then calls
Reply
in
s1
while
Begin
is still waiting, so the
Reply
call fails.
[StateScope(Scope.MultiplayerSession)]public class Relay : CloudBehaviour{ public async Task<string> Begin([CloudCodeService] IRelay relay, string otherSessionId) => await relay.Forward(Context.ScopeId).ForScopeAsync(otherSessionId); [CloudCodeAccess(Access.Service)] public async Task<string> Forward([CloudCodeService] IRelay relay, string startSessionId) => await relay.Reply().ForScopeAsync(startSessionId); [CloudCodeAccess(Access.Service)] public string Reply() => "done";}
The Editor displays a warning on a
ForScopeAsync
call when it can tell from your code that the call targets a scope instance that's still waiting, as in this example. The warning lists the calls in between. The Editor can't detect every case, so a call can still fail at runtime without a warning.
To get a result from another scope instance, return the result to the caller instead of calling back into the caller's scope instance.

Requirements

To call another CloudBehaviour through its generated interface, you must do the following:
  • Put both CloudBehaviours in the same module. If the target is in another module, refer to Call a CloudBehaviour in another module.
  • Mark the injected parameter with
    [CloudCodeService]
    . Otherwise, the build fails. Refer to Inject services into an RPC.
  • Register the target's interface in your module's
    ICloudCodeSetup
    . In this example, call
    config.AddPlayerRecordClient()
    . Refer to Register the generated interface.
  • Pass only the endpoint's own arguments. The Editor removes every
    [CloudCodeService]
    parameter from
    I{Behaviour}
    , so the call has no argument for the injected parameter.
  • Give each CloudBehaviour class in the module a unique name, even across namespaces.
Note
A timer always runs on the CloudBehaviour that scheduled it, so calling
ScheduleAsync
on another CloudBehaviour's
I{Behaviour}
fails the build. To defer work on another CloudBehaviour, schedule your own endpoint and call
ForScopeAsync
from inside it. Refer to Timers in CloudBehaviours.

Additional resources