Justin808
Justin808

Reputation: 21512

How do a save Unity3d Mesh to file?

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?

Upvotes: 7

Views: 11226

Answers (1)

Everts
Everts

Reputation: 10701

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;
}

Upvotes: 8

Related Questions