Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static unsafe class UnityColliderSerialization
- {
- public static string GetSerializationPath(string name)
- {
- return string.Format("{0}/{1}.bin", Application.streamingAssetsPath, name);
- }
- public static BlobAssetReference<Collider> DeserializeCollider(string path)
- {
- // You do not have to pass a specific buffer-size to the reader. The
- //buffer is an optimiziation. You should avoid very small buffers, but
- //the default size is probably fine for your purpose.
- using (StreamBinaryReader reader = new StreamBinaryReader(path))
- {
- int length = reader.ReadInt();
- // We are deserializing the collider and want to keep it in memory,
- //hence the allocator should be persistent and we also definitely
- //should *not* free it immediately because we want to use the
- //collider later on: If we free the memory, we're essentially
- //accessing random values in memory.
- void* collider = UnsafeUtility.Malloc(length, 16, Allocator.Persistent);
- reader.ReadBytes(collider, length);
- return BlobAssetReference<Collider>.Create(collider, length);
- }
- }
- public static void SerializeCollider(Collider* collider, string path)
- {
- // The same note about the buffer size applies here as well. you don't have
- // to set it.
- using (StreamBinaryWriter writer = new StreamBinaryWriter(path))
- {
- writer.Write(collider->MemorySize);
- writer.WriteBytes(collider, collider->MemorySize);
- }
- }
- // These extensions methods are taken from BinarySerialization.cs in the Entities package.
- public static int ReadInt(this BinaryReader reader)
- {
- int value;
- reader.ReadBytes(&value, sizeof(int));
- return value;
- }
- public static void Write(this BinaryWriter writer, int value)
- {
- writer.WriteBytes(&value, sizeof(int));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement