multiplayer refactor
This commit is contained in:
40
Runtime/Engine/Code/Network/DataSerializationUtils.cs
Normal file
40
Runtime/Engine/Code/Network/DataSerializationUtils.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using Unity.Collections;
|
||||
using Unity.Collections.LowLevel.Unsafe;
|
||||
using Unity.Netcode;
|
||||
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>(NativeArray<byte> data, ref TEntity entity)
|
||||
where TEntity : ISerializableEntity {
|
||||
using NetworkBufferReader reader = new NetworkBufferReader(data);
|
||||
if (reader.HasNext(data.Length)) {
|
||||
entity.Deserialize(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user