S&box Wiki

Revision Difference

RPCs#544202

<cat>Code.Network</cat> <title>RPCs</title> # What Are RPCs? They're just network messages. The server sends a message to the client, when the client receives the message it calls a function. It's that simple. (RPC is short for Remote Procedure Call) <warning>You may need to turn prediction off before running a client RPC in some situations for it to work. Example: ``` using( Prediction.Off() ) { entity.ShowDeathScreen( "Killa04" ); } ``` </warning> # Example On entities you can mark a function as an RPC: ``` [ClientRpc] public void ShowDeathScreen( string killedName ) { Log.Info( "TODO SHOW DEATH SCREEN" ); } ``` Here Client tells us that this method should only ever be called on the client. So if you're on the server and you do this: ``` entity.ShowDeathScreen( "Killa04" ); ``` It gets called on the client version of the entity. We've done some magic in the background. <note>During compilation we've added an extra step in the RPC function that checks if we're being called serverside, and if we are it'll broadcast a message to every client which will call the method.</note> # Targeting Players We have a problem with the above example. We wouldn't want to show the death screen to every player. We'd want to show it to just one. The code generator has got you covered, it's created another function in the background which takes a target as the first argument. ``` entity.ShowDeathScreen( To.Single(deadPlayer), "Killa04" ); ``` Calling this will only call `ShowDeathScreen` on `deadPlayer`'s client. # Client to Server Here the client tells the Server a Vector3. Which will modify the calling client's Pawn rotation, and eye rotation. ``` [ServerCmd] public static void ClientVectorToServer( Vector3 lookAtPos ) { Entity pawn = ConsoleSystem.Caller.Pawn; pawn.Rotation = Rotation.LookAt( (lookAtPos - pawn.Position).WithZ( 0 ).Normal ); pawn.EyeRot = pawn.Rotation; } ``` Now you need to call this static function within the client-side code. For this example, it can be used in the Camera Controller Update function. ``` ClientVectorToServer( new Vector3( 10, 10, 10 ) ); ``` <note> Calling the function will be predicted automatically; so you will want to put Prediction.Off() around your function, as seen below. Calling the function will be predicted automatically; so you will want to put `Prediction.Off()` around your function, as seen below. ``` using( Prediction.Off() ) { ClientVectorToServer( new Vector3( 10, 10, 10 ) ); } ``` </note> # todo * Multicast messages