This section explains how to declare and use Network Variables by code.


  1. Using Network Variables directly


Network Variable must bound a type NetworkVariable<T> where T must be included into allowed types ( see Network Variables ).



 private NetworkVariable<string> variable = "";



  1. Once defined you can use it as if any other script variable



 this.variable = "This is a new string value";


 string variableValue = this.variable;



  1. Detecting Changes


You can detect when the object was updated on the passive instance to apply changes only when occur..



 this.variable.OnValueChange((string oldValue, string newValue) => {
  Debug.Log(string.Format("Value was updated from [ {0} ] to [ {1} ] ", oldValue, newValue));
 });



  1. Synchronizing local variables


ObjectNet allows to synchronization of network variables with local variables automatically. The following script allows you to keep a local variable synchronized with a network variable, no matter where you change the value, both variables will have the same value.



 string localVariable = "Start text";


 this.variable.OnSynchonize(() => { return this.localVariable; },
                            (string value) => { this.localVariable = value; });


 this.localVariable = "New value from local"; // In this case variable Network will also receive the new value "New value from local"
 this.variable = "New value from Network variable"; // In this case local variable will also receive the new value "New value from Network Variable"