S&box Wiki

Revision Difference

Network_Callbacks#545876

<cat>Code.Network</cat> <title>Network Callbacks</title> ⤶ ⤶ You can get a notification when a `[Net]` property has changed **clientside**. This is useful if you want to update something in the UI, or run some other logic when the variable changes on the client without having to poll for changes frequently. ⤶ # Supported Types⤶ ⤶ ## Classes⤶ ⤶ `Entity`, `NetworkComponent`, `string`⤶ ⤶ ## Primitive⤶ ⤶ `bool`, `byte`, `sbyte`, `char`, `double`, `float`, `int`, `uint`, `long`, `ulong`, `short`, `ushort`⤶ ⤶ ## Lists⤶ ⤶ Any `List<T>` is supported where `T` is any of the above classes or primitives with the exception of `NetworkComponent`, because they cannot be networked in a list. ⤶ # Usage⤶ ⤶ ⤶ ## Attribute⤶ ⤶ Add the `[OnChangedCallback]` attribute to your `[Net]` property.⤶ ⤶ ## Callback Method⤶ ⤶ Add a method to your `Entity` or `NetworkComponent` called `On[PropertyName]Changed()` where `[PropertyName]` is the name of your `[Net]` property.⤶ ⤶ # Example⤶ ⤶ Simply add the `[Change]` attribute alongside your `[Net]` property, by default this calls On[PropertyName]Changed.⤶ ⤶ ```csharp⤶ [Net, Change] ⤶ public string DataString { get; set; }⤶ ⤶ public void OnDataStringChanged( string oldValue, string newValue )⤶ {⤶ Log.Info( $"changed from {oldValue} to {newValue}" ); }⤶ ```⤶ ```csharp public partial class Unit : Entity⤶ [Net, Change( nameof( DoSomething ) )] ⤶ public string DataString { get; set; }⤶ ⤶ public void DoSomething( string oldValue, string newValue )⤶ { [Net, Local, OnChangedCallback] public bool IsGathering { get; private set; } ⤶ private void OnIsGatheringChanged()⤶ {⤶ if ( IsGathering )⤶ Log.Info( "I am now gathering." );⤶ else⤶ Log.Info( "I am no longer gathering." );⤶ }⤶ Log.Info( $"changed from {oldValue} to {newValue}" ); } ``````⤶