37 lines
1.2 KiB
C#
37 lines
1.2 KiB
C#
using Unity.Collections;
|
|
using UnityEngine.Assertions;
|
|
|
|
namespace RebootKit.Engine.Network {
|
|
public static class DataSerializationUtils {
|
|
public const int k_DefaultMessageSize = 256;
|
|
|
|
public static NativeArray<byte> Serialize<TEntity>(TEntity entity,
|
|
Allocator allocator = Allocator.Temp)
|
|
where TEntity : ISerializableEntity {
|
|
int size = entity.GetMaxBytes();
|
|
if (size < 0) {
|
|
size = k_DefaultMessageSize;
|
|
}
|
|
|
|
NativeArray<byte> data = new NativeArray<byte>(size, allocator);
|
|
|
|
using NetworkBufferWriter writer = new NetworkBufferWriter(data, 0);
|
|
Assert.IsTrue(writer.WillFit(size));
|
|
|
|
if (writer.WillFit(size)) {
|
|
entity.Serialize(writer);
|
|
return data;
|
|
}
|
|
|
|
return default;
|
|
}
|
|
|
|
public static void Deserialize<TEntity>(NativeSlice<byte> data, ref TEntity entity)
|
|
where TEntity : ISerializableEntity {
|
|
using NetworkBufferReader reader = new NetworkBufferReader(data);
|
|
if (reader.HasNext(data.Length)) {
|
|
entity.Deserialize(reader);
|
|
}
|
|
}
|
|
}
|
|
} |