In this lesson, you will learn how to transition from client-side input to server-side action by using ServerRpc to safely execute game events.
Understanding the Authority Gap
In a multiplayer environment, clients cannot simply "force" the game state to change—if a player clicks a button to spawn an item or open a door, the client must ask the server for permission. This is because the server holds the authoritative truth. If we let clients modify world state directly, we open the door to cheating and desynchronization. ServerRpc acts as the bridge that securely routes a "request" from the client to the server.
Implementing a ServerRpc
To trigger a server-side event, you must define a method within a NetworkBehaviour class and tag it with the [ServerRpc] attribute. When a client calls this method, the code execution "jumps" from the client's machine to the server.
Consider a scenario where a player interacts with a switch to spawn a crate:
public class InteractionHandler : NetworkBehaviour
{
[ServerRpc(RequireOwnership = false)]
private void RequestSpawnCrateServerRpc()
{
// This code now runs exclusively on the server
GameObject crate = Instantiate(cratePrefab);
crate.GetComponent<NetworkObject>().Spawn();
}
}
Key Considerations
- Permissions: Notice the
RequireOwnership = falseparameter. By default,ServerRpcrequires the client to own theNetworkObject. By setting this tofalse, you allow any client to trigger the event regardless of ownership. - Validation: Never trust input from a client blindly. Inside your
ServerRpcmethod, always add logic to validate that the request is legitimate (e.g., check if the player is close enough to the switch or has enough currency) before performing the action. - Execution Flow: Remember that the logic inside the
ServerRpcmethod is authoritative. Once the server processes the change, it will automatically propagate the resulting state to other clients via yourNetworkVariableorNetworkObjectsynchronization logic.
Key Takeaway: Use ServerRpc to send authoritative requests from clients to the server, ensuring that all state-changing game events are processed securely and synchronized across the network.