Is it posible to save mesh to json?

I am new in unity. I have a meshfilter. I need to save it in a json file but I don’t know how. Can someone help me?

I am not sure if this is the best solution, but to save/load a mesh at runtime as/from a JSON file, you can do something like this (maybe add further error handling):

If you want to save the mesh of an imported model, you may need to enable read/write access to the model in the model import settings or the properties of the mesh might not be available.

Then…

    // Create a serializable wrapper class for the mesh data
    // (class Mesh is sealed and not serializable)
    // all properties of this class must be public for the serializer
    [System.Serializable]
    public class MeshSaveData
    {
        public int[] triangles;
        public Vector3[] vertices;
        public Vector3[] normals;

        // add whatever properties of the mesh you need...

        public MeshSaveData(Mesh mesh)
        {
            this.vertices = mesh.vertices;
            this.triangles = mesh.triangles;
            this.normals = mesh.normals;
            // further properties...
        }
    }

In your GameObject (using the System.IO namespace):

    // modify this for each mesh saved
    string saveFileName = "/mesh.json";
    
    void SaveMesh()
    {
        string json = JsonUtility.ToJson(new MeshSaveData(GetComponent<MeshFilter>().sharedMesh));
        string savePath = Application.persistentDataPath + saveFileName;

        Debug.Log("saving mesh data to " + savePath);

        File.WriteAllText(savePath, json);
    }

    void LoadMesh()
    {
        string savePath = Application.persistentDataPath + saveFileName;

        if (File.Exists(savePath))
        {
            string json = File.ReadAllText(savePath);

            MeshSaveData savedMesh = JsonUtility.FromJson<MeshSaveData>(json);

            Debug.Log("loaded mesh data from " + savePath);

            Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
            mesh.vertices = savedMesh.vertices;
            mesh.triangles = savedMesh.triangles;
            mesh.normals = savedMesh.normals;
            //...
        }
    }

You could also try a JSON serialization framework, but i haven’t tried this.

You could serialise any data to JSON if thats what you want. Is that necessarily a good idea? Probably not.


There are much better plain text formats like OBJ that I would suggest you use, over trying to establish a proprietary format.


If you are really sold on JSON there are some JSON formats like gltf that would be better suited than creating a proprietary format.


Regardless the easiest way is to add NewtonsoftJson to your project and then use it to serialise your C# object then just write that string to a text file.