Created
April 10, 2023 11:13
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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