Skip to content

Instantly share code, notes, and snippets.

@zcyemi
Created June 12, 2018 13:17
Show Gist options
  • Save zcyemi/b90171186c06e3fb1f24ed5336f60ead to your computer and use it in GitHub Desktop.
Save zcyemi/b90171186c06e3fb1f24ed5336f60ead to your computer and use it in GitHub Desktop.
Unity mesh binary serialzation.
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[ExecuteInEditMode]
public class MeshSerialization : MonoBehaviour {
public Mesh MeshBox;
public Mesh MeshCapsule;
public Mesh MeshSphere;
public Mesh meshCynlinder;
public static MeshSerialization Inst;
public void Awake()
{
Inst = this;
}
private void Update()
{
if (Inst == null) Inst = this;
}
[CIS.CISTestEntry("MeshSeralize")]
public static void Seralize()
{
SaveMesh("D:/box.mesh",Inst.MeshBox);
SaveMesh("D:/capsule.mesh", Inst.MeshCapsule);
SaveMesh("D:/sphere.mesh", Inst.MeshSphere);
SaveMesh("D:/cylinder.mehs", Inst.meshCynlinder);
}
private static void SaveMesh(string filepath, Mesh mesh)
{
if (mesh == null) return;
if (File.Exists(filepath)) File.Delete(filepath);
var meshdata = new MeshData();
meshdata.VerticesCount = (uint)mesh.vertexCount;
meshdata.IndicesCount = mesh.GetIndexCount(0);
meshdata.Vertices = GetByteArray(mesh.vertices);
meshdata.IndicesData = GetByteArray(mesh.triangles);
var colors = new List<Color32>();
mesh.GetColors(colors);
meshdata.Color = GetByteArray(colors.ToArray());
meshdata.UV0 = GetByteArray(mesh.uv);
meshdata.ExtraInfo = mesh.name;
meshdata.SaveToFile(filepath);
}
public unsafe static byte[] GetByteArray<T>(T[] ary)
{
var len = ary.Length * Marshal.SizeOf(typeof(T));
byte[] data = new byte[len];
var handle = GCHandle.Alloc(ary, GCHandleType.Pinned);
Marshal.Copy(handle.AddrOfPinnedObject(), data, 0, len);
handle.Free();
return data;
}
}
[Serializable]
public class MeshData
{
public uint VerticesCount;
public uint IndicesCount;
public byte[] Vertices;
public byte[] Color;
public byte[] UV0;
public byte[] UV1;
public byte[] IndicesData;
public string ExtraInfo;
public static MeshData LoadFromFile(string filepath)
{
var formatter = new BinaryFormatter();
MeshData data = null;
using (FileStream filestream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
data = (MeshData)formatter.Deserialize(filestream);
filestream.Close();
}
return data;
}
public void SaveToFile(string filepath)
{
var formatter = new BinaryFormatter();
using (FileStream filestream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
formatter.Serialize(filestream, this);
filestream.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment