fix the c# script for unity below, make it to where it wont lag the main thread and…
- User
fix the c# script for unity below, make it to where it wont lag the main thread and crash the app (run it on its own thread)
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) { Transform[] trs = mainObj.GetComponentsInChildren(); ExporterRuntimeS.ExportGOToOBJ(trs,path,name); } }
public class ExporterRuntimeS : ScriptableObject { private static int vertexOffset = 0; private static int normalOffset = 0; private static int uvOffset = 0; //private static string mainPath = "Assets/GameObjectToOBJExportFolder";
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 {0}\n", kvp.Key); 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 {0}\n", relativeFile); } 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) { // 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; }
- Assistant
To prevent the export functionality from blocking the main thread in Unity (which could lead to sluggishness or a crash), you can move the blocking code inside a separate thread. However, Unity's API is generally not thread-safe, so you'll need to be careful with how you interact with Unity objects and APIs.
Here's how to modify your code using
System.Threading.Tasksfor asynchronous processing in Unity. This implementation will allow you to export your GameObject data in a non-blocking way while adhering to thread safety.using UnityEngine; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; public class ExporterRuntime : MonoBehaviour { public void ExportObj(GameObject mainObj, string path, string name) { Transform[] trs = mainObj.GetComponentsInChildren<Transform>(); // Start the export process as a Task Task.Run(() => ExporterRuntimeS.ExportGOToOBJ(trs, path, name)); } } public class ExporterRuntimeS : ScriptableObject { static int vertexOffset = 0; static int normalOffset = 0; 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 { name = mats[material].name, textureName = GetTextureName(mats[material]) }; materialList.Add(objMaterial.name, objMaterial); } catch (ArgumentException) { // Handle exception if the material already exists } 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 string GetTextureName(Material material) { #if UNITY_EDITOR return material.mainTexture ? UnityEditor.AssetDatabase.GetAssetPath(material.mainTexture) : null; #else return null; #endif } private static void Clear() { vertexOffset = 0; normalOffset = 0; uvOffset = 0; } 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 {0}\n", kvp.Key); 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; string relativeFile = Path.GetFileName(destinationFile); destinationFile = Path.Combine(folder, relativeFile); File.Copy(kvp.Value.textureName, destinationFile); sw.Write("map_Kd {0}\n", relativeFile); } 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) { mainPath += "/" + filename + "/"; System.IO.Directory.CreateDirectory(mainPath); int objCount = 0; var mfList = new List<MeshFilter>(); foreach (var trans in selection) { var meshFilters = trans.GetComponentsInChildren<MeshFilter>(); foreach (var meshFilter in meshFilters) { objCount++; mfList.Add(meshFilter); } } if (objCount > 0) { MeshFilter[] mf = mfList.ToArray(); if (string.IsNullOrEmpty(filename)) { 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: " + Path.Combine(mainPath, filename)); } else { Debug.Log("Error exporting. Make sure you selected the object."); } } } struct OMATRuntime { public string name; public string textureName; public Color cls; }Key Changes:
- I wrapped the export call (
ExporterRuntimeS.ExportGOToOBJ) withinTask.Run()in theExportObjmethod. This runs the export asynchronously in a separate thread. - I used
List<MeshFilter>instead ofArrayListfor better type safety and performance. - I ensured that path handling is done using
Path.Combine()for a safer path construction.
Note:
Remember that you should not modify any Unity objects or call Unity API functions from a different thread. If you need to perform any updates in the Unity scene after the export is finished, consider using
UnityMainThreadDispatcheror invoking methods back on the main thread after the task completes.Ensure you test this implementation thoroughly to handle potential exceptions that may arise from file operations or user input.
- I wrapped the export call (
- User
I have a progress bar that has a min value of 0 and a max value of 1 I want it to be the progress bar for current progress of export.
using UnityEngine; using System.Collections; using System.Text.RegularExpressions; using System.Collections.Generic; using System;
public class ExportRuntimeExample : MonoBehaviour { public GameObject Sim; // List to hold the direct children private List SimObjects = new List();
public static string SanitizeFilename(string filename) { // Define a regex pattern for invalid characters string invalidCharsPattern = @"[\\/:*?""<>|]"; // Use Regex to replace invalid characters with an empty string filename = Regex.Replace(filename, invalidCharsPattern, string.Empty); // Additionally, you can trim the filename to remove any leading or trailing whitespace filename = filename.Trim(); return filename; } void GetSimChildren() { Sim = FindSim(); // Clear the list before adding children SimObjects.Clear(); // Loop through each child of the parent foreach (Transform child in Sim.transform) { // Add the child to the list SimObjects.Add(child.gameObject); } } public GameObject FindSim() { GameObject sim = GameObject.FindGameObjectWithTag("TerrainOBJ"); return sim; } public void ExportSimBatch() { GetSimChildren(); if (SimObjects == null) { // Optionally log or handle the case where SimObjects is null return; } foreach (GameObject mesh in SimObjects) { if (!string.IsNullOrEmpty(mesh.name)) { try { ExportRuntime(mesh, SanitizeFilename(mesh.name)); } catch (Exception ex) { Debug.LogError($"Failed to export {mesh.name}: {ex.Message}"); } } } } public void ExportRuntime(GameObject Gameobject, string FolderName) { ExporterRuntime ex = this.gameObject.GetComponent<ExporterRuntime>(); ex.ExportObj(Gameobject, Application.streamingAssetsPath, FolderName); }}
- Assistant
To integrate a progress bar that updates during the export process, we need to adjust your
ExportSimBatchmethod and theExporterRuntimeclass to support progress reporting. We'll accomplish this by using a coroutine to both handle the export process and update the progress bar.Here's how you can implement it:
-
Setup a UI Progress Bar: First, make sure you have a UI Slider in your scene, which will act as the progress bar. You can set its
minValueto 0 andmaxValueto 1. Ensure you have a reference to the Slider in your script. If you don't have a Slider, you can create one via the Unity UI system. -
Modify
ExportRuntimeExampleClass: Update theExportSimBatchmethod to use a coroutine for exporting and updating the progress bar.
Here's how you can modify your code:
Modified Code
using UnityEngine; using System.Collections; using System.Text.RegularExpressions; using System.Collections.Generic; using System; public class ExportRuntimeExample : MonoBehaviour { public GameObject Sim; private List<GameObject> SimObjects = new List<GameObject>(); public UnityEngine.UI.Slider progressBar; // Reference to the UI Slider for progress public static string SanitizeFilename(string filename) { // Define a regex pattern for invalid characters string invalidCharsPattern = @"[\\/:*?""<>|]"; filename = Regex.Replace(filename, invalidCharsPattern, string.Empty); return filename.Trim(); } void GetSimChildren() { Sim = FindSim(); SimObjects.Clear(); // Add all children to SimObjects foreach (Transform child in Sim.transform) { SimObjects.Add(child.gameObject); } } public GameObject FindSim() { return GameObject.FindGameObjectWithTag("TerrainOBJ"); } public void ExportSimBatch() { // Start the coroutine to export with progress StartCoroutine(ExportWithProgress()); } private IEnumerator ExportWithProgress() { GetSimChildren(); if (SimObjects == null || SimObjects.Count == 0) { Debug.LogWarning("No simulation objects found for export."); yield break; } int totalObjects = SimObjects.Count; for (int i = 0; i < totalObjects; i++) { GameObject mesh = SimObjects[i]; if (!string.IsNullOrEmpty(mesh.name)) { try { ExportRuntime(mesh, SanitizeFilename(mesh.name)); } catch (Exception ex) { Debug.LogError($"Failed to export {mesh.name}: {ex.Message}"); } } // Update the progress bar progressBar.value = (float)(i + 1) / totalObjects; yield return null; // Wait until the next frame to avoid blocking } Debug.Log("Export complete."); } public void ExportRuntime(GameObject Gameobject, string FolderName) { ExporterRuntime ex = this.gameObject.GetComponent<ExporterRuntime>(); if (ex != null) { ex.ExportObj(Gameobject, Application.streamingAssetsPath, FolderName); } else { Debug.LogError("ExporterRuntime component not found on the GameObject."); } } }Explanation of Changes:
-
UI Slider Reference: Make sure to link the
Slidercomponent in the Unity Editor to theprogressBarfield ofExportRuntimeExample. -
Refactored Export Logic:
- The
ExportSimBatchmethod starts a coroutine namedExportWithProgress. - Inside the coroutine, the export operations are conducted as before, but now after each export, the progress bar's value is updated according to the current export index.
yield return nullis used to allow the frame to update without blocking.
- The
-
Error Handling: Added checks for
SimObjectsto avoid null reference exceptions and provide warnings if no objects are found.
Important Note:
To see the progress of the export in real-time, ensure that your export functionality runs quickly enough not to block the main thread substantially. If the export takes too long, consider implementing asynchronous file operations or batch exporting strategies to minimize blocking.
-
- User
please modify the code to not lag the application
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) { Transform[] trs = mainObj.GetComponentsInChildren(); ExporterRuntimeS.ExportGOToOBJ(trs,path,name); } }
public class ExporterRuntimeS : ScriptableObject { private static int vertexOffset = 0; private static int normalOffset = 0; private static int uvOffset = 0; //private static string mainPath = "Assets/GameObjectToOBJExportFolder";
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 {0}\n", kvp.Key); 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 {0}", relativeFile); } 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) { // 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; }
- Assistant
To modify the code so that the exporting process does not lag the application, we will use asynchronous programming with tasks. This allows the export operation to run on a separate thread while keeping the main Unity thread responsive. Here's how to do that in your script:
- Use
asyncandawaitto handle asynchronous operations for the export function. - Make sure that Unity-specific operations (like modifying game objects or UI) are executed on the main thread.
Here’s the modified code for your
ExporterRuntimeandExporterRuntimeSclasses that runs the export in an asynchronous manner:using UnityEngine; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; public class ExporterRuntime : MonoBehaviour { public async void ExportObj(GameObject mainObj, string path, string name) { Transform[] trs = mainObj.GetComponentsInChildren<Transform>(); await ExporterRuntimeS.ExportGOToOBJAsync(trs, path, name); } } 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 { name = mats[material].name, textureName = null }; #if UNITY_EDITOR if (mats[material].mainTexture) objMaterial.textureName = UnityEditor.AssetDatabase.GetAssetPath(mats[material].mainTexture); #endif materialList.Add(objMaterial.name, objMaterial); } catch (ArgumentException) { // Handle already existing material names. } 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 async Task MaterialsToFileAsync(Dictionary<string, OMATRuntime> materialList, string folder, string filename) { using (StreamWriter sw = new StreamWriter(Path.Combine(folder, $"{filename}.mtl"))) { foreach (var kvp in materialList) { await sw.WriteLineAsync($"\nnewmtl {kvp.Key}\n"); await sw.WriteLineAsync("Ka 1.0 1.0 1.0\n"); await sw.WriteLineAsync("Kd 1.0 1.0 1.0\n"); await sw.WriteLineAsync("Ks 1.0 1.0 1.0\n"); await sw.WriteLineAsync("d 1.0\n"); await sw.WriteLineAsync("Ns 0.0\n"); await sw.WriteLineAsync("illum 2\n"); if (kvp.Value.textureName != null) { string destinationFile = kvp.Value.textureName; string relativeFile = Path.GetFileName(destinationFile); string fullDestinationPath = Path.Combine(folder, relativeFile); // Perform file copy on a separate thread. File.Copy(kvp.Value.textureName, fullDestinationPath); await sw.WriteLineAsync($"map_Kd {relativeFile}\n"); } await sw.WriteLineAsync(); } } } private static async Task MeshesToFileAsync(MeshFilter[] mf, string folder, string filename) { Dictionary<string, OMATRuntime> materialList = PrepareFileWrite(); using (StreamWriter sw = new StreamWriter(Path.Combine(folder, $"{filename}.obj"))) { await sw.WriteLineAsync($"mtllib ./{filename}.mtl\n"); for (int i = 0; i < mf.Length; i++) { await sw.WriteAsync(MeshToString(mf[i], materialList)); } } await MaterialsToFileAsync(materialList, folder, filename); } public static async Task ExportGOToOBJAsync(Transform[] selection, string mainPath, string filename) { mainPath = Path.Combine(mainPath, filename); Directory.CreateDirectory(mainPath); List<MeshFilter> mfList = new List<MeshFilter>(); foreach (var trans in selection) { var meshFilters = trans.GetComponentsInChildren<MeshFilter>(); mfList.AddRange(meshFilters); } if (mfList.Count > 0) { MeshFilter[] mf = mfList.ToArray(); filename = string.IsNullOrEmpty(filename) ? selection[0].gameObject.name : filename; await MeshesToFileAsync(mf, mainPath, filename); Debug.Log($"Exported: {mainPath}/{filename}"); } else { Debug.LogWarning("Error exporting. Make sure you selected the object."); } } } struct OMATRuntime { public string name; public string textureName; public Color cls; }Key Modifications:
-
Asynchronous Method Signatures: Changed the
ExportObjandExportGOToOBJmethods toasyncand their returning types toTask. This allows methods to run in a non-blocking manner. -
Await for File Writes: Used
awaitforWriteLineAsyncand similar methods when writing to files in theMaterialsToFileAsyncandMeshesToFileAsyncmethods. -
Directory and File Operations: Wrapped potentially long-running operations in
async Taskmethods, which allows these to run without freezing the main thread. -
UI Thread Safety: Whenever you implement progress updates or UI changes based on export status, ensure those are called back on the main thread.
Notes:
- This example performs file IO operations in an asynchronous manner, which is more responsive but can still be influenced by filesystem performance. If you anticipate the export to be substantial, consider implementing progress updates via events or additional logic.
- When using this method for file operations, ensure that access to file paths and directories is thread-safe if files may be modified or accessed concurrently.
- Use
- User
for any filenames that are empty give them a unique filename
using UnityEngine; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks;
public class ExporterRuntime : MonoBehaviour { public async void ExportObj(GameObject mainObj, string path, string name) { Transform[] trs = mainObj.GetComponentsInChildren(); await ExporterRuntimeS.ExportGOToOBJAsync(trs, path, name); } }
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 { name = mats[material].name, textureName = null }; #if UNITY_EDITOR if (mats[material].mainTexture) objMaterial.textureName = UnityEditor.AssetDatabase.GetAssetPath(mats[material].mainTexture); #endif materialList.Add(objMaterial.name, objMaterial); } catch (ArgumentException) { // Handle already existing material names. } 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 async Task MaterialsToFileAsync(Dictionary<string, OMATRuntime> materialList, string folder, string filename) { using (StreamWriter sw = new StreamWriter(Path.Combine(folder, $"{filename}.mtl"))) { foreach (var kvp in materialList) { await sw.WriteLineAsync($"\nnewmtl {kvp.Key}\n"); await sw.WriteLineAsync("Ka 1.0 1.0 1.0\n"); await sw.WriteLineAsync("Kd 1.0 1.0 1.0\n"); await sw.WriteLineAsync("Ks 1.0 1.0 1.0\n"); await sw.WriteLineAsync("d 1.0\n"); await sw.WriteLineAsync("Ns 0.0\n"); await sw.WriteLineAsync("illum 2\n"); if (kvp.Value.textureName != null) { string destinationFile = kvp.Value.textureName; string relativeFile = Path.GetFileName(destinationFile); string fullDestinationPath = Path.Combine(folder, relativeFile); // Perform file copy on a separate thread. File.Copy(kvp.Value.textureName, fullDestinationPath); await sw.WriteLineAsync($"map_Kd {relativeFile}\n"); } await sw.WriteLineAsync(); } } } private static async Task MeshesToFileAsync(MeshFilter[] mf, string folder, string filename) { Dictionary<string, OMATRuntime> materialList = PrepareFileWrite(); using (StreamWriter sw = new StreamWriter(Path.Combine(folder, $"{filename}.obj"))) { await sw.WriteLineAsync($"mtllib ./{filename}.mtl\n"); for (int i = 0; i < mf.Length; i++) { await sw.WriteAsync(MeshToString(mf[i], materialList)); } } await MaterialsToFileAsync(materialList, folder, filename); } public static async Task ExportGOToOBJAsync(Transform[] selection, string mainPath, string filename) { mainPath = Path.Combine(mainPath, filename); Directory.CreateDirectory(mainPath); List<MeshFilter> mfList = new List<MeshFilter>(); foreach (var trans in selection) { var meshFilters = trans.GetComponentsInChildren<MeshFilter>(); mfList.AddRange(meshFilters); } if (mfList.Count > 0) { MeshFilter[] mf = mfList.ToArray(); filename = string.IsNullOrEmpty(filename) ? selection[0].gameObject.name : filename; await MeshesToFileAsync(mf, mainPath, filename); Debug.Log($"Exported: {mainPath}/{filename}"); } else { Debug.LogWarning("Error exporting. Make sure you selected the object."); } }}
struct OMATRuntime { public string name; public string textureName; public Color cls; }
- Assistant
To generate a unique filename for any meshes that may have empty names during the export process, you can modify the logic where you're assigning the filename in the
ExportGOToOBJAsyncmethod. If a name is empty or not provided, we can append a unique identifier, such as a timestamp or a GUID (Globally Unique Identifier), ensuring that it will be distinct and valid.Here are the modifications to handle that scenario:
Updated Code Snippet
using UnityEngine; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; public class ExporterRuntime : MonoBehaviour { public async void ExportObj(GameObject mainObj, string path, string name) { Transform[] trs = mainObj.GetComponentsInChildren<Transform>(); await ExporterRuntimeS.ExportGOToOBJAsync(trs, path, name); } } 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 { name = mats[material].name, textureName = null }; #if UNITY_EDITOR if (mats[material].mainTexture) objMaterial.textureName = UnityEditor.AssetDatabase.GetAssetPath(mats[material].mainTexture); #endif materialList.Add(objMaterial.name, objMaterial); } catch (ArgumentException) { // Handle already existing material names. } 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 async Task MaterialsToFileAsync(Dictionary<string, OMATRuntime> materialList, string folder, string filename) { using (StreamWriter sw = new StreamWriter(Path.Combine(folder, $"{filename}.mtl"))) { foreach (var kvp in materialList) { await sw.WriteLineAsync($"\nnewmtl {kvp.Key}\n"); await sw.WriteLineAsync("Ka 1.0 1.0 1.0\n"); await sw.WriteLineAsync("Kd 1.0 1.0 1.0\n"); await sw.WriteLineAsync("Ks 1.0 1.0 1.0\n"); await sw.WriteLineAsync("d 1.0\n"); await sw.WriteLineAsync("Ns 0.0\n"); await sw.WriteLineAsync("illum 2\n"); if (kvp.Value.textureName != null) { string destinationFile = kvp.Value.textureName; string relativeFile = Path.GetFileName(destinationFile); string fullDestinationPath = Path.Combine(folder, relativeFile); // Perform file copy on a separate thread. File.Copy(kvp.Value.textureName, fullDestinationPath); await sw.WriteLineAsync($"map_Kd {relativeFile}\n"); } await sw.WriteLineAsync(); } } } private static async Task MeshesToFileAsync(MeshFilter[] mf, string folder, string filename) { Dictionary<string, OMATRuntime> materialList = PrepareFileWrite(); using (StreamWriter sw = new StreamWriter(Path.Combine(folder, $"{filename}.obj"))) { await sw.WriteLineAsync($"mtllib ./{filename}.mtl\n"); for (int i = 0; i < mf.Length; i++) { await sw.WriteAsync(MeshToString(mf[i], materialList)); } } await MaterialsToFileAsync(materialList, folder, filename); } public static async Task ExportGOToOBJAsync(Transform[] selection, string mainPath, string filename) { mainPath = Path.Combine(mainPath, filename); Directory.CreateDirectory(mainPath); List<MeshFilter> mfList = new List<MeshFilter>(); foreach (var trans in selection) { var meshFilters = trans.GetComponentsInChildren<MeshFilter>(); mfList.AddRange(meshFilters); } if (mfList.Count > 0) { MeshFilter[] mf = mfList.ToArray(); // Check if the filename is empty and generate a unique one if true if (string.IsNullOrEmpty(filename)) { // Generate a unique filename using the current timestamp filename = "ExportedMesh_" + DateTime.Now.ToString("yyyyMMddHHmmss"); } await MeshesToFileAsync(mf, mainPath, filename); Debug.Log($"Exported: {mainPath}/{filename}"); } else { Debug.LogWarning("Error exporting. Make sure you selected the object."); } } } struct OMATRuntime { public string name; public string textureName; public Color cls; }Key Modifications:
- Unique Filename Generation:
- In the
ExportGOToOBJAsyncmethod, I added a condition to check iffilenameis empty or null. - If it is, a unique filename is generated using a timestamp formatted as
yyyyMMddHHmmss. This ensures that the filename is unique for each export and provides a clear indication of when the export occurred.
- In the
Additional Considerations:
- Timestamp Format: You can adjust the format of the timestamp to fit your naming conventions.
- Collision Handling: If your application could generate multiple exports at the exact same second, consider adding a counter or GUID to ensure uniqueness further.
- UI Feedback: If you're implementing this in a user-facing application, consider providing feedback to the user about the generated filename, especially if it's defaulting to the timestamp.
Make sure to validate the filename in a broader context if you have any specific requirements about the characters used.
- Unique Filename Generation: