S&box Wiki

Revision Difference

RPCs#560456

<cat>Code.Network</cat> <title>RPCs</title> ⤶ # What Are RPCs?⤶ ⤶ RPC is short for remote procedure call. 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.⤶ ⤶ # 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. ⤶ ⤶ ## RPCs on static classes⤶ You can also use RPCs on static classes.⤶ ⤶ ```CS⤶ public static partial class MyStaticClass⤶ {⤶ [ClientRpc]⤶ public static void MyStaticMethod()⤶ {⤶ Log.Info("Hello!");⤶ }⤶ }⤶ ```⤶ This can then be invoked from the server using `MyStaticClass.MyStaticMethod()`.⤶ ⤶ <note>During compilation we've added an extra step in the RPC function that checks if we're being called serverside, and if so, then 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⤶ ⤶ Client-to-Server RPCs aren't enabled yet, but you can send [console commands](https://wiki.facepunch.com/sbox/Commands) instead.⤶ ⤶ # Limitations⤶ ⤶ - RPCs are only supported on types derived from `Entity`, `EntityComponent`, or on all static functions.⤶ - If called on an entity, the entity must exist on the client and the entity must not be culled by vis[](https://github.com/sboxgame/issues/issues/2099). ⤶ <note>Page needs to be entirely rewritten for the scene system, lets wait until networking is more finalized though.</note>