Skip to content

Instantly share code, notes, and snippets.

@Kellojo
Created April 10, 2023 11:13
Show Gist options
  • Save Kellojo/1e62b747b892a94a96f0c98540bbbc48 to your computer and use it in GitHub Desktop.
Save Kellojo/1e62b747b892a94a96f0c98540bbbc48 to your computer and use it in GitHub Desktop.
A simple struct that can hold a JSON and implementes the INetworkSerializable interface of Unitys Netcode for GameObjects multiplayer package. Can be used to serialize an arbitrary class/struct and transfer it over the network using RPCs, network variables and more. Licensed under the MIT license.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Unity.Netcode;
[System.Serializable]
public struct RuntimeState : INetworkSerializable {
JObject jObject;
string JSON;
public RuntimeItemState(object state) {
JSON = "";
jObject = null;
Set(state);
}
public T Get<T>() {
return JsonConvert.DeserializeObject<T>(JSON);
}
public void Set(object state) {
var json = JsonConvert.SerializeObject(state);
jObject = null;
JSON = json;
}
public override string ToString() {
return JSON;
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter {
serializer.SerializeValue(ref JSON);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment