Server & Client RPCs
An RPC (Remote Procedure Call) lets one machine trigger a method that runs on another. Netcode gives you two directions.
public class PlayerShooter : NetworkBehaviour
{
[ServerRpc]
void FireServerRpc()
{
// Runs on the server only, the server owns the truth.
SpawnBullet();
FireClientRpc();
}
[ClientRpc]
void FireClientRpc()
{
// Runs on every client, e.g. to play a muzzle-flash effect.
PlayMuzzleFlash();
}
void Update()
{
if (IsOwner && Input.GetButtonDown("Fire1"))
FireServerRpc();
}
}
The rules
[ServerRpc]methods are called by a client (usually the owner) but always execute on the server, name them with aServerRpcsuffix.[ClientRpc]methods are called by the server and execute on every connected client, suffixClientRpc.- By default a
ServerRpccan only be called by the object's owner, setRequireOwnership = falseto allow any client to call it. - Never trust a client to decide game outcomes, a client calls a
ServerRpcto request an action, the server validates and applies it, then tells everyone via aClientRpc.