S&box Wiki

Revision Difference

Networked_Types#530537

<cat>Code.Misc</cat> <title>Networked Types</title> Networked types allow you to synchronize class members between client and server, this is most commonly used for entities but can be used on any class that is derived from `NetworkClass` #Creating a networked member Adding the `[Net]` or any of the other attributes listed below to a property will mark it to be networked. ``` [Net] public float HeadSize { get; set; } ``` <warning>Classes containing networked members have to be marked as `partial` in order to work properly.</warning> There are several different attributes you can use instead of `[Net]` that each behave slightly differently: * `[Net]` - Networks to everyone * `[NetPredicted]` - Same as `[Net]` but allows the value to be predicted * `[NetLocal]` - Only networks to the player it's set on or `Entity.Owner` * `[NetLocalPredicted]` - Same as `[NetLocal]` but allows the value to be predicted #Custom types Before you can start networking your own types you have to make sure they're supported. Entities are supported by default and you don't have to worry about them. For non-entity classes the easiest method is to have it inherit from `NetworkClass` but if you want to you can do it the manual way as well. #The manual way (Serialization) This method is mainly used for structs but you can use it for classes as well if you'd like. ##Structs Structs are fairly simple to set up as you just have to add two member functions, one for writing and one for reading the serialized data. ``` public void Write( BinaryWriter writer ) { writer.Write( (float)x ); writer.Write( (float)y ); writer.Write( (float)z ); } public Vector3 Read( BinaryReader reader ) { return new Vector3( reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle() ); } ``` ##Classes For classes you have to be a bit more crafty, members don't work here since a class can be `null` and we have to handle updating existing instances. Static functions work just fine for this. ``` public static class MyClassExtension { public static void Write( this MyClass self, System.IO.BinaryWriter writer ) { if ( self == null ) { writer.Write( false ); return; } writer.Write( true ); writer.Write( self.Age ); writer.Write( self.Sex ); writer.Write( self.Location ); } public static MyClass Read( this MyClass self, System.IO.BinaryReader reader ) { int notNull = reader.ReadBoolean(); if ( notNull == 0 ) return null; if ( self == null ) self = new MyClass(); self.Age = self.Age.Read( reader ); self.Sex = self.Sex.Read( reader ); self.Location = self.Location.Read( reader ); return self; } } ``` [Extension methods](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) can als be used here (and are used in the example) to let you add support to classes you're unable to access for some reason.