- Home /
Serialize a mesh
Hi,
I am currently capturing a user mesh from a Kinect (I am making a mesh by subsampling the user depth map). I would like to save the frames to a file in order to reproduce them in another context. My first approach is serialization. Apparently, all objects in my graph should be serializable, so I am asked to serialize the Mesh class, the Vector3 class, and so on. Is there another way to do this?
My current approach is having a Frame class which simply contains a timestamp and a mesh. I construct a List of Frame objects and I attempt to save it when the application is closed.
[A note to moderators: I would appreciate some feedback if this question gets rejected...]
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
[RequireComponent (typeof(MeshFilter), (typeof(MeshRenderer)))]
public class meshRecorder : MonoBehaviour {
Mesh mesh;
public String fileName;
List <Frame> frames;
public int expectedTime = 60;
public int expectedFrameRate = 30;
void Start () {
// Estimated number of frames:
int numFrames = expectedTime * expectedFrameRate;
print ("Expected number of frames: " + numFrames);
frames = new List<Frame> (Mathf.RoundToInt (1.5f * numFrames)); // Overestimated initial capacity.
mesh = GetComponent <MeshFilter> ().mesh;
// FileName
if (String.IsNullOrEmpty( fileName)) {
fileName = DateTime.Now.ToString("yyyy_mm_dd_hh_mm_ss");
print ("will save to " + fileName);
}
}
// Update is called once per frame
void Update () {
//Frame f = new Frame (Time.time, mesh);
Frame f = new Frame (Time.time, mesh.triangles, mesh.vertices);
frames.Add (f);
}
void OnApplicationQuit(){
// Open stream for writing.
Stream stream = File.Open (fileName + ".mst", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter ();
bf.Serialize (stream, frames);
}
}
[Serializable()]
public class Frame {
float time; // En segundos.
int [] triangles;
Vector3 [] vertices;
//Mesh mesh;
/*public Frame( float t, Mesh m){
time = t;
mesh = m;
}*/
public Frame (float t, int [] _triangles, Vector3 [] _vertices){
time = t;
triangles = _triangles;
vertices = _vertices;
}
}
Answer by sergiobd · Jul 17, 2015 at 03:43 PM
Answering to my own question here:
As vertices are vectors, I decided to save them as a 2-dimensional array of floats (of size [3, numVertices]).
Your answer
![](https://koobas.hobune.stream/wayback/20220611230414im_/https://answers.unity.com/themes/thub/images/avi.jpg)