struct OMATRuntime
{
public string name;
public string textureName;
public Color cls;
}
To ensure that the OBJ export operation runs asynchronously and does not block the main thread, you can use Unity's Coroutine facilities. Below is an updated version of your original script that utilizes a Coroutine to handle the export operation using Unity's threading model:
csharp
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
public class ExporterRuntime : MonoBehaviour
{
public void ExportObj(GameObject mainObj, string path, string name)
{
StartCoroutine(ExportCoroutine(mainObj, path, name));
}
private IEnumerator ExportCoroutine(GameObject mainObj, string path, string name)
{
Transform[] trs = mainObj.GetComponentsInChildren<Transform>();
yield return new WaitForEndOfFrame(); // Optional: yields the coroutine to the next frame if needed.
// You can log or show progress here, if desired.
ExporterRuntimeS.ExportGOToOBJ(trs, path, name);
// Log completion
Debug.Log("Export completed.");
}
}
public class ExporterRuntimeS : ScriptableObject
{
private static int vertexOffset = 0;
private static int normalOffset = 0;
private static int uvOffset = 0;
private static string MeshToString(MeshFilter mf, Dictionary<string, OMATRuntime> materialList)
{
Mesh m = mf.sharedMesh;
Material[] mats = mf.GetComponent<Renderer>().sharedMaterials;
StringBuilder sb = new StringBuilder();
sb.Append("g ").Append(mf.name).Append("\n");
foreach (Vector3 lv in m.vertices)
{
Vector3 wv = mf.transform.TransformPoint(lv);
sb.Append(string.Format("v {0} {1} {2}\n", -wv.x, wv.y, wv.z));
}
sb.Append("\n");
foreach (Vector3 lv in m.normals)
{
Vector3 wv = mf.transform.TransformDirection(lv);
sb.Append(string.Format("vn {0} {1} {2}\n", -wv.x, wv.y, wv.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");
try
{
OMATRuntime objMaterial = new OMATRuntime();
objMaterial.name = mats[material].name;
#if UNITY_EDITOR
if (mats[material].mainTexture)
objMaterial.textureName = UnityEditor.EditorUtility.GetAssetPath(mats[material].mainTexture);
else
#endif
objMaterial.textureName = null;
materialList.Add(objMaterial.name, objMaterial);
}
catch (ArgumentException)
{
}
int[] triangles = m.GetTriangles(material);
for (int i = 0; i < triangles.Length; i += 3)
{
sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n",
triangles[i] + 1 + vertexOffset, triangles[i + 1] + 1 + normalOffset, triangles[i + 2] + 1 + uvOffset));
}
}
vertexOffset += m.vertices.Length;
normalOffset += m.normals.Length;
uvOffset += m.uv.Length;
return sb.ToString();
}
private static void Clear()
{
vertexOffset = 0;
normalOffset = 0;
uvOffset = 0;
}
private static Dictionary<string, OMATRuntime> PrepareFileWrite()
{
Clear();
return new Dictionary<string, OMATRuntime>();
}
private static void MaterialsToFile(Dictionary<string, OMATRuntime> materialList, string folder, string filename)
{
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".mtl"))
{
foreach (KeyValuePair<string, OMATRuntime> kvp in materialList)
{
sw.Write("\n");
sw.Write($"newmtl {kvp.Key}\n");
sw.Write("Ka 1.0 1.0 1.0\n");
sw.Write("Kd 1.0 1.0 1.0\n");
sw.Write("Ks 1.0 1.0 1.0\n");
sw.Write("d 1.0\n");
sw.Write("Ns 0.0\n");
sw.Write("illum 2\n");
if (kvp.Value.textureName != null)
{
string destinationFile = kvp.Value.textureName;
int indexStrip = destinationFile.LastIndexOf('/');
if (indexStrip >= 0)
destinationFile = destinationFile.Substring(indexStrip + 1).Trim();
string relativeFile = destinationFile;
destinationFile = folder + "/" + destinationFile;
File.Copy(kvp.Value.textureName, destinationFile);
sw.Write($"map_Kd {relativeFile}\n");
}
sw.Write("\n\n\n");
}
}
}
private static void MeshesToFile(MeshFilter[] mf, string folder, string filename)
{
Dictionary<string, OMATRuntime> materialList = PrepareFileWrite();
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".obj"))
{
sw.Write("mtllib ./" + filename + ".mtl\n");
for (int i = 0; i < mf.Length; i++)
{
sw.Write(MeshToString(mf[i], materialList));
}
}
MaterialsToFile(materialList, folder, filename);
}
public static void ExportGOToOBJ(Transform[] selection, string mainPath, string filename)
{
// Uncomment this line if you need a default export path
// mainPath = "Assets/GameObjectToOBJExportFolder";
mainPath += "/" + filename + "/";
System.IO.Directory.CreateDirectory(mainPath);
int objCount = 0;
ArrayList mfList = new ArrayList();
for (int i = 0; i < selection.Length; i++)
{
Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
for (int m = 0; m < meshfilter.Length; m++)
{
objCount++;
mfList.Add(meshfilter[m]);
}
}
if (objCount > 0)
{
MeshFilter[] mf = new MeshFilter[mfList.Count];
for (int i = 0; i < mfList.Count; i++)
{
mf[i] = (MeshFilter)mfList[i];
}
if (filename.Equals(""))
{
filename = selection[0].gameObject.name;
}
int indexstrip = filename.LastIndexOf('/');
if (indexstrip >= 0)
{
filename = filename.Substring(indexstrip + 1).Trim();
}
MeshesToFile(mf, mainPath, filename);
Debug.Log("Exported: " + mainPath + "/" + filename);
#if UNITY_EDITOR
UnityEditor.AssetDatabase.SaveAssets();
UnityEditor.AssetDatabase.Refresh();
#endif
}
else
{
Debug.Log("Error exporting. Make sure you selected the object.");
}
}
}
struct OMATRuntime
{
public string name;
public string textureName;
public Color cls;
}
Changes Made:
Coroutine Implementation: The ExportObj method starts a coroutine (ExportCoroutine) that performs the export operation. Doing this allows the operation to yield control back to the main thread, preventing frame drops while the export is in progress.
Yielding for Performance: The coroutine can yield to allow other operations to continue, although I've added a simple frame yield with WaitForEndOfFrame(). You can customize this to fit any logic you want for asynchronous behavior.
Output Messages: Added debug logs to indicate progress (you can expand this to show more detailed progress if needed).
This approach keeps the logic of your original implementation intact while ensuring that potentially lengthy processing happens off the main thread without blocking game execution.
I have a progress bar min value 0 max value is 1 can you add that into code for progress?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
public class ExporterRuntime : MonoBehaviour
{
public void ExportObj(GameObject mainObj, string path, string name)
{
StartCoroutine(ExportCoroutine(mainObj, path, name));
}
code
private IEnumerator ExportCoroutine(GameObject mainObj, string path, string name)
{
Transform[] trs = mainObj.GetComponentsInChildren<Transform>();
yield return new WaitForEndOfFrame(); // Optional: yields the coroutine to the next frame if needed.
// You can log or show progress here, if desired.
ExporterRuntimeS.ExportGOToOBJ(trs, path, name);
// Log completion
Debug.Log("Export completed.");
}
}
public class ExporterRuntimeS : ScriptableObject
{
private static int vertexOffset = 0;
private static int normalOffset = 0;
private static int uvOffset = 0;
code
private static string MeshToString(MeshFilter mf, Dictionary<string, OMATRuntime> materialList)
{
Mesh m = mf.sharedMesh;
Material[] mats = mf.GetComponent<Renderer>().sharedMaterials;
StringBuilder sb = new StringBuilder();
sb.Append("g ").Append(mf.name).Append("\n");
foreach (Vector3 lv in m.vertices)
{
Vector3 wv = mf.transform.TransformPoint(lv);
sb.Append(string.Format("v {0} {1} {2}\n", -wv.x, wv.y, wv.z));
}
sb.Append("\n");
foreach (Vector3 lv in m.normals)
{
Vector3 wv = mf.transform.TransformDirection(lv);
sb.Append(string.Format("vn {0} {1} {2}\n", -wv.x, wv.y, wv.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");
try
{
OMATRuntime objMaterial = new OMATRuntime();
objMaterial.name = mats[material].name;
#if UNITY_EDITOR
UnityEditor.AssetDatabase.SaveAssets();
UnityEditor.AssetDatabase.Refresh();
#endif
}
else
{
Debug.Log("Error exporting. Make sure you selected the object.");
}
}
}
struct OMATRuntime
{
public string name;
public string textureName;
public Color cls;
}
To incorporate a progress bar that updates its value between a minimum of 0 and a maximum of 1 during the export process, we can modify the ExportCoroutine method to communicate progress updates back to the main thread. Below is an example of how you could achieve this, assuming you have a UI Slider component set up in your Unity scene for showing the progress.
First, you'll need to declare a Slider variable to manipulate the progress bar from the Unity UI. Here’s how you can update your existing code:
Updated Code
csharp
using UnityEngine;
using UnityEngine.UI; // Add this for Slider support
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
public class ExporterRuntime : MonoBehaviour
{
public Slider progressBar; // This is your UI Slider for progress
public void ExportObj(GameObject mainObj, string path, string name)
{
StartCoroutine(ExportCoroutine(mainObj, path, name));
}
private IEnumerator ExportCoroutine(GameObject mainObj, string path, string name)
{
Transform[] trs = mainObj.GetComponentsInChildren<Transform>();
yield return new WaitForEndOfFrame(); // Optional: yields the coroutine to the next frame if needed.
// Start export and update the progress bar
yield return StartCoroutine(ExporterRuntimeS.ExportGOToOBJ(trs, path, name, progressBar));
// Log completion
Debug.Log("Export completed.");
}
}
public class ExporterRuntimeS : ScriptableObject
{
private static int vertexOffset = 0;
private static int normalOffset = 0;
private static int uvOffset = 0;
private static string MeshToString(MeshFilter mf, Dictionary<string, OMATRuntime> materialList)
{
Mesh m = mf.sharedMesh;
Material[] mats = mf.GetComponent<Renderer>().sharedMaterials;
StringBuilder sb = new StringBuilder();
sb.Append("g ").Append(mf.name).Append("\n");
foreach (Vector3 lv in m.vertices)
{
Vector3 wv = mf.transform.TransformPoint(lv);
sb.Append(string.Format("v {0} {1} {2}\n", -wv.x, wv.y, wv.z));
}
sb.Append("\n");
foreach (Vector3 lv in m.normals)
{
Vector3 wv = mf.transform.TransformDirection(lv);
sb.Append(string.Format("vn {0} {1} {2}\n", -wv.x, wv.y, wv.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");
try
{
OMATRuntime objMaterial = new OMATRuntime();
objMaterial.name = mats[material].name;
#if UNITY_EDITOR
if (mats[material].mainTexture)
objMaterial.textureName = UnityEditor.EditorUtility.GetAssetPath(mats[material].mainTexture);
else
#endif
objMaterial.textureName = null;
materialList.Add(objMaterial.name, objMaterial);
}
catch (ArgumentException) { }
int[] triangles = m.GetTriangles(material);
for (int i = 0; i < triangles.Length; i += 3)
{
sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n",
triangles[i] + 1 + vertexOffset, triangles[i + 1] + 1 + normalOffset, triangles[i + 2] + 1 + uvOffset));
}
}
vertexOffset += m.vertices.Length;
normalOffset += m.normals.Length;
uvOffset += m.uv.Length;
return sb.ToString();
}
private static void Clear()
{
vertexOffset = 0;
normalOffset = 0;
uvOffset = 0;
}
private static Dictionary<string, OMATRuntime> PrepareFileWrite()
{
Clear();
return new Dictionary<string, OMATRuntime>();
}
private static void MaterialsToFile(Dictionary<string, OMATRuntime> materialList, string folder, string filename)
{
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".mtl"))
{
foreach (KeyValuePair<string, OMATRuntime> kvp in materialList)
{
sw.Write("\n");
sw.Write($"newmtl {kvp.Key}\n");
sw.Write("Ka 1.0 1.0 1.0\n");
sw.Write("Kd 1.0 1.0 1.0\n");
sw.Write("Ks 1.0 1.0 1.0\n");
sw.Write("d 1.0\n");
sw.Write("Ns 0.0\n");
sw.Write("illum 2\n");
if (kvp.Value.textureName != null)
{
string destinationFile = kvp.Value.textureName;
int indexStrip = destinationFile.LastIndexOf('/');
if (indexStrip >= 0)
destinationFile = destinationFile.Substring(indexStrip + 1).Trim();
string relativeFile = destinationFile;
destinationFile = folder + "/" + destinationFile;
File.Copy(kvp.Value.textureName, destinationFile);
sw.Write($"map_Kd {relativeFile}\n");
}
sw.Write("\n\n\n");
}
}
}
private static void MeshesToFile(MeshFilter[] mf, string folder, string filename)
{
Dictionary<string, OMATRuntime> materialList = PrepareFileWrite();
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".obj"))
{
sw.Write("mtllib ./" + filename + ".mtl\n");
for (int i = 0; i < mf.Length; i++)
{
sw.Write(MeshToString(mf[i], materialList));
// Update progress (scaled to range 0 - 1)
yield return new WaitForEndOfFrame(); // Yields to allow other operations to run.
}
}
MaterialsToFile(materialList, folder, filename);
}
public static IEnumerator ExportGOToOBJ(Transform[] selection, string mainPath, string filename, Slider progressBar)
{
// Uncomment this line if you need a default export path
// mainPath = "Assets/GameObjectToOBJExportFolder";
mainPath += "/" + filename + "/";
System.IO.Directory.CreateDirectory(mainPath);
int objCount = 0;
ArrayList mfList = new ArrayList();
for (int i = 0; i < selection.Length; i++)
{
Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
for (int m = 0; m < meshfilter.Length; m++)
{
objCount++;
mfList.Add(meshfilter[m]);
}
}
if (objCount > 0)
{
MeshFilter[] mf = new MeshFilter[mfList.Count];
for (int i = 0; i < mfList.Count; i++)
{
mf[i] = (MeshFilter)mfList[i];
}
if (string.IsNullOrEmpty(filename))
{
filename = selection[0].gameObject.name;
}
int indexstrip = filename.LastIndexOf('/');
if (indexstrip >= 0)
{
filename = filename.Substring(indexstrip + 1).Trim();
}
// Total number of meshes for progress calculation
int totalMeshes = mf.Length;
for (int i = 0; i < totalMeshes; i++)
{
MeshesToFile(mf, mainPath, filename);
// Update progress bar
float progress = (float)(i + 1) / totalMeshes; // Compute progress
progressBar.value = progress;
yield return null; // Yielding to proccess each frame
}
Debug.Log("Exported: " + mainPath + "/" + filename);
#if UNITY_EDITOR
UnityEditor.AssetDatabase.SaveAssets();
UnityEditor.AssetDatabase.Refresh();
#endif
}
else
{
Debug.Log("Error exporting. Make sure you selected the object.");
}
}
}
struct OMATRuntime
{
public string name;
public string textureName;
public Color cls;
}
Explanation of Changes
Progress Bar Slider: A Slider reference (public Slider progressBar) is included in the ExporterRuntime class. This is how you can manage the progress visually in UI.
Updating Progress: In the ExportGOToOBJ method, after processing each mesh with MeshesToFile, the slider's value is updated to reflect the current progress of the operation, scaled between 0 and 1.
Yielding Progress Updates: After updating the progress bar, yield return null; allows Unity to continue processing the rest of the frame while updating the UI.
Setup Instructions
In your Unity scene, add a Slider UI element and link it to the progressBar field of the ExporterRuntime script in the Unity inspector.
Make sure the minimum and maximum values of the Slider component are set to 0 and 1, respectively.
Now, when you execute the export, your progress bar should update smoothly based on the completion of the export process.
Not yet included in a published release.
materialList.Add(objMaterial.name, objMaterial);
}
catch (ArgumentException)
{
}
int[] triangles = m.GetTriangles(material);
for (int i = 0; i < triangles.Length; i += 3)
{
sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n",
triangles[i] + 1 + vertexOffset, triangles[i + 1] + 1 + normalOffset, triangles[i + 2] + 1 + uvOffset));
}
}
vertexOffset += m.vertices.Length;
normalOffset += m.normals.Length;
uvOffset += m.uv.Length;
return sb.ToString();
}
private static void Clear()
{
vertexOffset = 0;
normalOffset = 0;
uvOffset = 0;
}
private static Dictionary<string, OMATRuntime> PrepareFileWrite()
{
Clear();
return new Dictionary<string, OMATRuntime>();
}
private static void MaterialsToFile(Dictionary<string, OMATRuntime> materialList, string folder, string filename)
{
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".mtl"))
{
foreach (KeyValuePair<string, OMATRuntime> kvp in materialList)
{
sw.Write("\n");
sw.Write($"newmtl {kvp.Key}\n");
sw.Write("Ka 1.0 1.0 1.0\n");
sw.Write("Kd 1.0 1.0 1.0\n");
sw.Write("Ks 1.0 1.0 1.0\n");
sw.Write("d 1.0\n");
sw.Write("Ns 0.0\n");
sw.Write("illum 2\n");
if (kvp.Value.textureName != null)
{
string destinationFile = kvp.Value.textureName;
int indexStrip = destinationFile.LastIndexOf('/');
if (indexStrip >= 0)
destinationFile = destinationFile.Substring(indexStrip + 1).Trim();
string relativeFile = destinationFile;
destinationFile = folder + "/" + destinationFile;
File.Copy(kvp.Value.textureName, destinationFile);
sw.Write($"map_Kd {relativeFile}\n");
}
sw.Write("\n\n\n");
}
}
}
private static void MeshesToFile(MeshFilter[] mf, string folder, string filename)
{
Dictionary<string, OMATRuntime> materialList = PrepareFileWrite();
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".obj"))
{
sw.Write("mtllib ./" + filename + ".mtl\n");
for (int i = 0; i < mf.Length; i++)
{
sw.Write(MeshToString(mf[i], materialList));
}
}
MaterialsToFile(materialList, folder, filename);
}
public static void ExportGOToOBJ(Transform[] selection, string mainPath, string filename)
{
// Uncomment this line if you need a default export path
// mainPath = "Assets/GameObjectToOBJExportFolder";
mainPath += "/" + filename + "/";
System.IO.Directory.CreateDirectory(mainPath);
int objCount = 0;
ArrayList mfList = new ArrayList();
for (int i = 0; i < selection.Length; i++)
{
Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
for (int m = 0; m < meshfilter.Length; m++)
{
objCount++;
mfList.Add(meshfilter[m]);
}
}
if (objCount > 0)
{
MeshFilter[] mf = new MeshFilter[mfList.Count];
for (int i = 0; i < mfList.Count; i++)
{
mf[i] = (MeshFilter)mfList[i];
}
if (filename.Equals(""))
{
filename = selection[0].gameObject.name;
}
int indexstrip = filename.LastIndexOf('/');
if (indexstrip >= 0)
{
filename = filename.Substring(indexstrip + 1).Trim();
}
MeshesToFile(mf, mainPath, filename);
Debug.Log("Exported: " + mainPath + "/" + filename);