简体   繁体   中英

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?

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

您可以使用该编辑器脚本,并从MeshFilter组件上下文菜单中另存为.asset

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM