Network RPCs
Remote Procedure Call (shorten as RPC) is used to invoke code on other network clients. For example, call server method from client or vice versa: call method on all clients from server. This is useful to synchronize state or invoke certain action over the network (eg. player attack, chat message, etc.). RPC methods can be normally called from gameplay code but inner logic might be executed only on other clients.
To declare RPC use NetworkRpc attribute on function with Server or Client value set. Each RPC can also specify the transport channel to use (Unreliable, UnreliableOrdered, Reliable, ReliableOrdered). Flax.Build codegen will inject custom code before the method body which will invoke the method properly on remote clients. Example RPCs:
Tip
RPCs can be used only in networked objects (registered via NetworkReplicator.AddObject) and in types which code module is marked with Network tag.
RPC Concepts
- Client RPC
- Can be called only by server or host
- Is sent to all connected clients that have registered the RPC object instance and are matching custom
TargetIds(if provided viaNetworkRpcParams) - Can be both sent and executed locally on host (both server and client)
- Server RPC
- Can be called only by client or host
- Is sent to server only
- You can use
SenderIdfield fromNetworkRpcParamsto detect which client send that RPC
RPC Examples
// Example RPC invoked on server-only
[NetworkRpc(Server = true)]
public void SetSequenceIndex(ushort value)
{
_currentSequence = value;
}
// Example RPC invoked on clients with Unreliable channel (message might not arrive but will have less lag)
[NetworkRpc(Client = true, Channel = NetworkChannelType.Unreliable)]
public void CallClientRPC(string text, uint[] ids)
{
Debug.Log("Got msg from server: " + text);
}
RPC Context Parameters
Network RPCs can use contextual parameters as input to detect who sends the message or as output to send a message to a specific set of clients. Those identifiers are based on NetworkClient.ClientId, you can use NetworkManager.GetClient to get the client for a specific id. Use NetworkRpcParams structure parameter as follows:
// Example RPC invoked on server that logs the client who send this message
[NetworkRpc(Server = true)]
public void SetSequenceIndex(ushort value, NetworkRpcParams rpc = new NetworkRpcParams())
{
Debug.Log("Got msg on server from clientId: " + rpc.SenderId);
}
// Example RPC invoked on clients
[NetworkRpc(Client = true)]
public void CallClientRPC(string text, NetworkRpcParams rpc = new NetworkRpcParams())
{
Debug.Log("Got msg from server: " + text);
}
// Server method that invokes CallClientRPC only on specific list of clients
public void CallSpecificClients()
{
var rpc = new NetworkRpcParams
{
TargetIds = new uint[] { 1, 3 }, // NetworkClient.ClientId
};
CallClientRPC("hello", rpc);
}