- Home /
 
.Obj Exporter with .Mtl
Hello, thank you in advance!
I am trying to export a mesh during runtime using KeliHlodversson's script on the wiki. You can find it here: ObjExporter In short, how do I modify this runtime script so that it also exports the material file?
I get the Obj to export fine but I am having trouble creating the .mtl file for referencing a texture. It seems like the material exporting is expanded upon in the Editor script, so my next attempt is to try and butcher that to be used at runtime. I would love any suggestions! This is a great opportunity for me to learn, but It's all way over my head so I don't know where to start really.
Here's the simple exporter that I got working. It only makes the .obj file, but strangely it is referencing the materials. I think it is referencing them for another purpose however.
 using UnityEngine;
 using System.Collections;
 using System.IO;
 using System.Text;
  
 public class ObjExporter {
  
     public static string MeshToString(MeshFilter mf) {
         Mesh m = mf.mesh;
         Material[] mats = mf.renderer.sharedMaterials;
  
         StringBuilder sb = new StringBuilder();
  
         sb.Append("g ").Append(mf.name).Append("\n");
         foreach(Vector3 v in m.vertices) {
             sb.Append(string.Format("v {0} {1} {2}\n",v.x,v.y,v.z));
         }
         sb.Append("\n");
         foreach(Vector3 v in m.normals) {
             sb.Append(string.Format("vn {0} {1} {2}\n",v.x,v.y,v.z));
         }
         sb.Append("\n");
         foreach(Vector3 v in m.uv) {
             sb.Append(string.Format("vt {0} {1}\n",v.x,v.y));
         }
         for (int material=0; material < m.subMeshCount; material ++) {
             sb.Append("\n");
             sb.Append("usemtl ").Append(mats[material].name).Append("\n");
             sb.Append("usemap ").Append(mats[material].name).Append("\n");
  
             int[] triangles = m.GetTriangles(material);
             for (int i=0;i<triangles.Length;i+=3) {
                 sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", 
                     triangles[i]+1, triangles[i+1]+1, triangles[i+2]+1));
             }
         }
         return sb.ToString();
     }
  
     public static void MeshToFile(MeshFilter mf, string filename) {
         using (StreamWriter sw = new StreamWriter(filename)) 
         {
             sw.Write(MeshToString(mf));
         }
     }
 }
 
              hey, i know it's 6 years old but could you find a answer? i would really need this ^^'
Your answer