StrixBehaviourOnStrixSerialize Method |
Namespace: SoftGear.Strix.Unity.Runtime
public virtual void OnStrixSerialize( StrixSerializationProperties properties )
In this example we use OnStrixSerialize and OnStrixDeserialize to synchronize a game object's scale. StrixSerializationProperties does not support custom classes and structures such as Vector3 so we will serialize x, y, and z separately.
First, in Start method we register readable names for the scale vector component using RegisterIndexOfProperty(String, Int32). It is recommended to use negative index values, because we need to avoid collisions with the property indexes defined by Strix, and Strix libraries use positive values. In order to minimize network packet size, we want to use values with the smallest absolute values possible. We choose -1, -2, and -3 in this example.
In Update we check if we are the owner of the object using isSync. If yes, then we change the local scale of the object based on the movement of the mouse wheel. Then we override both OnStrixSerialize and OnStrixDeserialize, and use them to write and read the scale values. OnStrixSerialize is called on the object owner's client with the frequency defined by sendRate of StrixReplicator attached to this object. In it we take the current local scale values and put them into the serialization properties storage using Set(String, Object, String) and the string keys "Scale X", "Scale Y", and "Scale Z" that we have registered in the Start method. On the other clients, OnStrixDeserialize is called where we read the values back with GetT(String, T) and apply them to the transform.
As an option, we could have also used Set(Int32, Object, String) and GetT(Int32, T) overloads and -1, -2, and -3 values directly, instead of registering them with string keys beforehand.
using SoftGear.Strix.Unity.Runtime; using UnityEngine; public class StrixSerializeExample : StrixBehaviour { private void Start() { StrixSerializationProperties.RegisterIndexOfProperty("Scale X", -1); StrixSerializationProperties.RegisterIndexOfProperty("Scale Y", -2); StrixSerializationProperties.RegisterIndexOfProperty("Scale Z", -3); } private void Update() { if (isSync) { if (Input.mouseScrollDelta.y > 0) transform.localScale *= 1.1f; else if (Input.mouseScrollDelta.y < 0) transform.localScale /= 1.1f; } } public override void OnStrixSerialize(StrixSerializationProperties properties) { properties.Set("Scale X", transform.localScale.x); properties.Set("Scale Y", transform.localScale.y); properties.Set("Scale Z", transform.localScale.z); base.OnStrixSerialize(properties); } public override void OnStrixDeserialize(StrixSerializationProperties properties) { base.OnStrixDeserialize(properties); float x = 0f, y = 0f, z = 0f; properties.Get("Scale X", ref x); properties.Get("Scale Y", ref y); properties.Get("Scale Z", ref z); transform.localScale = new Vector3(x, y, z); } }