S&box Wiki

Revision Difference

Setting_Up_Networking#560436

<title>Setting Up Networking</title>⤶ ⤶ # Setting Up The Scene⤶ ⤶ Create a GameObject and give it the Network Helper component. The NetworkHelper component is an provided example of how to handle setting up a server and spawning players. It requires a prefab for the player and spawn points in the scene.⤶ Create several more empty GameObjects to act as spawn points and drag them into the Network Helper.⤶ <upload src="b543b/8dc2ab7bea28d16.png" size="20166" name="image.png" />⤶ ⤶ # Creating A Player⤶ ⤶ Create a separate GameObject and give it a SkinnedModelRenderer. Then create a new component and add the following code.⤶ ```⤶ public sealed class PlayerComponent : Component⤶ {⤶ [Sync][Property] int ColorIndex { get; set; } = 0;⤶ [Property] List<Color> Colors { get; set; }⤶ protected override void OnUpdate()⤶ {⤶ Components.Get<SkinnedModelRenderer>().Tint = Colors[ColorIndex];⤶ if ( IsProxy )⤶ return;⤶ ⤶ if ( Input.Pressed( "Jump" ) )⤶ ColorIndex++;⤶ if ( ColorIndex + 1 >= Colors.Count )⤶ ColorIndex = 0; ⤶ }⤶ }⤶ ```⤶ This is a simple player component which will change the model's colour whenever the space bar is pressed (make sure to setup the colours in the editor). There are two key networking related parts to this code. The `ColorIndex` value has a `[Sync]` attribute. This allows for the value to be networked across all clients. More information can be found [here](https://docs.facepunch.com/s/sbox-dev/doc/sync-properties-jKFHwTGVgR).⤶ ⤶ The update function also checked for `IsProxy`. This value will be true if the GameObject currently being updated is owned by a different client or none at all. Details on ownership in general are on the docs [here](https://docs.facepunch.com/s/sbox-dev/doc/ownership-7rMV3FABuV). ⤶ ⤶ Once you've set the player up, save it as a prefab and then place it into the NetworkHelper.⤶ ⤶ You can now run the game in the editor and open a new instance to test the multiplayer.⤶ <upload src="b543b/8dc2ab9a9d9346e.png" size="24028" name="image.png" />⤶ ⤶ <upload src="b543b/8dc2ab9cbd4a5e1.png" size="1227134" name="image.png" />⤶ # Documentation⤶ ⤶ A cheat sheet for networking can be found [here](https://docs.facepunch.com/s/sbox-dev/doc/networking-multiplayer-kaVboe3yRD) on the official documentation.