Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created May 27, 2023 12:31
Show Gist options
  • Select an option

  • Save unitycoder/b8e7cf60f0928d3960cb24ed7603c843 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/b8e7cf60f0928d3960cb24ed7603c843 to your computer and use it in GitHub Desktop.
Unity ExportMeshToOBJ
// https://forum.unity.com/threads/export-unity-mesh-to-obj-or-fbx-format.222690/#post-9041305
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System.Text;
 
public class ExportMeshToOBJ : ScriptableObject
{
    [MenuItem("GameObject/Export to OBJ")]
    static void ExportToOBJ()
    {
        GameObject obj = Selection.activeObject as GameObject;
        if (obj == null)
        {
            Debug.Log("No object selected.");
            return;
        }
 
        MeshFilter meshFilter = obj.GetComponent<MeshFilter>();
        if (meshFilter == null)
        {
            Debug.Log("No mesh found in selected GameObject.");
            return;
        }
 
        string path = EditorUtility.SaveFilePanel("Export OBJ", "", obj.name, "obj");
        Mesh mesh = meshFilter.sharedMesh;
        StringBuilder sb = new StringBuilder();
 
        foreach(Vector3 v in mesh.vertices)
        {
            sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, v.z));
        }
        foreach(Vector3 v in mesh.normals)
        {
            sb.Append(string.Format("vn {0} {1} {2}\n", v.x, v.y, v.z));
        }
        for (int material=0; material < mesh.subMeshCount; material++)
        {
            sb.Append(string.Format("\ng {0}\n", obj.name));
            int[] triangles = mesh.GetTriangles(material);
            for (int i = 0; i < triangles.Length; i += 3)
            {
                sb.Append(string.Format("f {0}/{0} {1}/{1} {2}/{2}\n",
                triangles[i] + 1,
                triangles[i + 1] + 1,
                triangles[i + 2] + 1));
            }
        }
        StreamWriter writer = new StreamWriter(path);
        writer.Write(sb.ToString());
        writer.Close();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment