Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. public static unsafe class UnityColliderSerialization
  2. {
  3.     public static string GetSerializationPath(string name)
  4.     {
  5.         return string.Format("{0}/{1}.bin", Application.streamingAssetsPath, name);
  6.     }
  7.  
  8.     public static BlobAssetReference<Collider> DeserializeCollider(string path)
  9.     {
  10.         // You do not have to pass a specific buffer-size to the reader. The
  11.         //buffer is an optimiziation. You should avoid very small buffers, but
  12.         //the default size is probably fine for your purpose.
  13.  
  14.         using (StreamBinaryReader reader = new StreamBinaryReader(path))
  15.         {
  16.             int length = reader.ReadInt();
  17.             //  We are deserializing the collider and want to keep it in memory,
  18.             //hence the allocator should be persistent and we also definitely
  19.             //should *not* free it immediately because we want to use the
  20.             //collider later on: If we free the memory, we're essentially
  21.             //accessing random values in memory.
  22.             void* collider = UnsafeUtility.Malloc(length, 16, Allocator.Persistent);
  23.             reader.ReadBytes(collider, length);
  24.             return BlobAssetReference<Collider>.Create(collider, length);
  25.         }
  26.     }
  27.  
  28.     public static void SerializeCollider(Collider* collider, string path)
  29.     {
  30.         // The same note about the buffer size applies here as well. you don't have
  31.         // to set it.
  32.         using (StreamBinaryWriter writer = new StreamBinaryWriter(path))
  33.         {
  34.             writer.Write(collider->MemorySize);
  35.             writer.WriteBytes(collider, collider->MemorySize);
  36.         }
  37.     }
  38.  
  39.     // These extensions methods are taken from BinarySerialization.cs in the Entities package.
  40.     public static int ReadInt(this BinaryReader reader)
  41.     {
  42.         int value;
  43.         reader.ReadBytes(&value, sizeof(int));
  44.         return value;
  45.     }
  46.  
  47.     public static void Write(this BinaryWriter writer, int value)
  48.     {
  49.         writer.WriteBytes(&value, sizeof(int));
  50.     }    
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement