- Home /
When and how to use [ClientRpc] and [Command]
Hello, so I've been looking at the unity documentation trying to understand networking, but I'm a little confused about [ClientRpc] and [Command].
Lets say I have a player with a simple move script Eg:
[Command]
void CmdMove()
{
//Do move stuff here
}
Is using the Command right in this case, or should I use ClientRpc?
If I want to spawn an object into unity. Do I use a command to tell the server? How do the other players know it was spawned?
So my main question is when and how do I use these commands. Also would [Client] need to be joined when using this?
Answer by Bunny83 · Sep 27, 2017 at 08:12 AM
A method with the Command attribute is ment to be called from a client but is are actually executed on the server.
A method with the ClientRPC attribute is ment to be called from the server but are executed on all clients instead.
Keep in mind that the method is bound to the object where the NetworkBehaviour is attached to. So if Player1 sends a command "CmdMoveForward" the command is executed on the server only on the object that is accociated with Player1. Likewise when the server calls a ClientRPC methhod RpcMovePlayer on the object accociated with Player3, this method is called on all clients on the Player3 object.
So commands are generally used to tell the server what you want to do and clientrpcs are used by the server to tell all clients what actually has happened.
This general approach is called an authoritative server as the server actually determines what happens.
So roughly speaking:
Commands tell the server what a client wants to change.
ClientRpcs tell the clients what the server has decided to do.
This allows the server to check all user input (the commands it receives) and ignore invalid input.
Ok that's cleared quite a bit of my confusion, thanks.
But if I tell the server to move forward with [Command] how do other players know that the player moved. Only the server know?
Consult the Photon documentation. Photon is a third party networking solution which I have never used. Though as far as I know it's very similar to Unity's old Raknet networking engine.