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
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 module | Use the generated interface and |
| A CloudBehaviour in another scope instance, in another module | Call it as a Cloud Code module endpoint. Refer to Call a CloudBehaviour in another module. |
| The same CloudBehaviour in the current scope instance | Call the method directly, the same as any other C# method. |
| A different CloudBehaviour in the current scope instance | You 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 calls | You can't call back into that scope instance with |
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 interface for every CloudBehaviour in your module. Inject the interface with , then call a member on the interface to get back an that hasn't run yet. To run the , pass the target's scope ID to .
I{Behaviour}[CloudCodeService]ICallICallForScopeAsync(scopeId)An does nothing until you run it. If you create an and never call or on it, the build fails.
ICallICallForScopeAsyncScheduleAsyncThe following example shows a -scoped that updates each player's at the end of a match. is -scoped because it belongs to one player and outlives any single match:
MultiplayerSessionMatchRoomPlayerRecordPlayerRecordPlayer[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[StateScope]entry.KeyScope.PlayerPlayerRecordForScopeAsyncContext.ScopeIdAwaiting 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 . In this example, each player receives their updated . For more information, refer to Control synchronization manually.
AutoSynchronizePlayerRecordGet a scope ID
Read the scope ID to pass to from the CloudBehaviour's :
ForScopeAsyncContextTarget scope | Scope ID | Notes |
|---|---|---|
| | The ID of the player making the current call. For the other players in a session, use |
| | Only available when the calling CloudBehaviour is |
When another CloudBehaviour calls the endpoint, doesn't contain a player ID, because the call uses the calling CloudBehaviour's service token. In a -scoped CloudBehaviour, read the owner's player ID from instead.
Context.PlayerIdPlayerContext.ScopeIdRestrict access to the target endpoint
A cross-behaviour call arrives with no player identity. The player ID you pass to selects only which scope instance runs the endpoint. The player ID doesn't make the call on that player's behalf.
ForScopeAsyncThe target is still an endpoint that a client can call directly. Mark the target so no player can call it directly. Refer to Access control in CloudBehaviours.
[CloudCodeAccess(Access.Service)]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 , the call fails immediately. If you pass
ForScopeAsync, the build fails. If you pass another value that matches the current scope ID, the call throws anContext.ScopeIdat runtime.InvalidOperationException - 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 error.
Gateway Timeout
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, and . An endpoint in calls an endpoint in and waits for the result. If the endpoint in then calls back into , can't run the call from until the endpoint in finishes, and the endpoint in is waiting for . Neither endpoint could finish, because each would wait for the other. This situation is a deadlock.
s1s2s1s2s2s1s1s2s1s1s2To prevent the deadlock, a call into a scope instance that's earlier in the current chain of calls, such as , fails immediately with an . The exception message starts with . The call fails even if the endpoint in doesn't await its call to .
ForScopeAsyncs1InvalidOperationExceptionForScopeAsync cycles1s2In the following example, the endpoint runs in session and awaits the endpoint in session . then calls in while is still waiting, so the call fails.
Begins1Forwards2ForwardReplys1BeginReply[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 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.
ForScopeAsyncTo 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 . Otherwise, the build fails. Refer to Inject services into an RPC.
[CloudCodeService] - Register the target's interface in your module's . In this example, call
ICloudCodeSetup. Refer to Register the generated interface.config.AddPlayerRecordClient() - Pass only the endpoint's own arguments. The Editor removes every parameter from
[CloudCodeService], so the call has no argument for the injected parameter.I{Behaviour} - Give each CloudBehaviour class in the module a unique name, even across namespaces.