Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skibitsky/90cb0f9c7e8a87ddbaa57615c4560c28 to your computer and use it in GitHub Desktop.
Save skibitsky/90cb0f9c7e8a87ddbaa57615c4560c28 to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
namespace Salday.UnityExtensions
{
public static class SerializationExtesions
{
public static byte[] SerializeQuaternion(this Quaternion quat)
{
byte[] arr = new byte[16];
var x = BitConverter.GetBytes(quat.x);
var y = BitConverter.GetBytes(quat.y);
var z = BitConverter.GetBytes(quat.z);
var w = BitConverter.GetBytes(quat.w);
Array.Copy(x, 0, arr, 0, 4);
Array.Copy(y, 0, arr, 4, 4);
Array.Copy(z, 0, arr, 8, 4);
Array.Copy(w, 0, arr, 12, 4);
return arr;
}
public static Quaternion DeserializeQuaternion(this byte[] arr)
{
if (arr == null) throw new ArgumentNullException("arr");
if (arr.Length != 16) throw new ArgumentException("arr");
return arr.DeserializeQuaternion(0);
}
public static Quaternion DeserializeQuaternion(this byte[] arr, int startIndex)
{
if (arr == null) throw new ArgumentNullException("arr");
if (arr.Length - 16 - startIndex < 0) throw new IndexOutOfRangeException();
var x = BitConverter.ToSingle(arr, 0 + startIndex);
var y = BitConverter.ToSingle(arr, 4 + startIndex);
var z = BitConverter.ToSingle(arr, 8 + startIndex);
var w = BitConverter.ToSingle(arr, 12 + startIndex);
return new Quaternion(x, y, z, w);
}
public static byte[] SerializeVector3(this Vector3 vec)
{
byte[] arr = new byte[12];
var x = BitConverter.GetBytes(vec.x);
var y = BitConverter.GetBytes(vec.y);
var z = BitConverter.GetBytes(vec.z);
Array.Copy(x, 0, arr, 0, 4);
Array.Copy(y, 0, arr, 4, 4);
Array.Copy(z, 0, arr, 8, 4);
return arr;
}
public static Vector3 DeserializeVector3(this byte[] arr)
{
if (arr == null) throw new ArgumentNullException("arr");
if (arr.Length != 12) throw new ArgumentException("arr");
return arr.DeserializeVector3(0);
}
public static Vector3 DeserializeVector3(this byte[] arr, int startIndex)
{
if (arr == null) throw new ArgumentNullException("arr");
if (arr.Length - 12 - startIndex < 0) throw new IndexOutOfRangeException();
var xPos = BitConverter.ToSingle(arr, 0 + startIndex);
var yPos = BitConverter.ToSingle(arr, 4 + startIndex);
var zPos = BitConverter.ToSingle(arr, 8 + startIndex);
return new Vector3(xPos, yPos, zPos);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment