Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do a save Unity3d Mesh to file?

Tags:

c#

unity3d

At runtime I create a Mesh. I would like to save this so it's an asset in my project so I don't have to re-create it every time.

How can I save a Mesh created at run-time into my Asset folder?

like image 713
Justin808 Avatar asked Feb 27 '16 19:02

Justin808


People also ask

How do you copy a mesh in Unity?

var copy = new Mesh(); foreach(var property in typeof(Mesh). GetProperties())


1 Answers

You can use that Mesh Serializer: http://wiki.unity3d.com/index.php?title=MeshSerializer2

public static void CacheItem(string url, Mesh mesh)
{
    string path = Path.Combine(Application.persistentDataPath, url);
    byte [] bytes = MeshSerializer.WriteMesh(mesh, true);
    File.WriteAllBytes(path, bytes);
}

It won't save into the Asset folder since this one does not exist anymore at runtime. You would most likely save it to the persistent data path, which is meant to store data, actually.

Then you can retrieve it just going the other way around:

public static Mesh GetCacheItem(string url)
{
    string path = Path.Combine(Application.persistentDataPath, url);
    if(File.Exists(path) == true)
    {
        byte [] bytes = File.ReadAllBytes(path);
        return MeshSerializer.ReadMesh(bytes);
    }
    return null;
}
like image 161
Everts Avatar answered Sep 25 '22 16:09

Everts