Runtime_OBJExporter.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #if UNITY_EDITOR
  2. using System.IO;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using VacuumShaders.TerrainToMesh;
  6. public class Runtime_OBJExporter : MonoBehaviour
  7. {
  8. public Terrain terrain;
  9. public int vertexCountHorizontal = 10;
  10. public int vertexCountVertical = 10;
  11. // Use this for initialization
  12. void Start()
  13. {
  14. float time = Time.realtimeSinceStartup;
  15. //Cointins OBJ data
  16. string strOBJ = TerrainToMeshConverter.TerrainToOBJ(terrain, vertexCountHorizontal, vertexCountVertical);
  17. Debug.Log("OBJ convertion in: " + (Time.realtimeSinceStartup- time) + " sec");
  18. //Create directory
  19. if (Directory.Exists(GetGenerateDirectory()) == false)
  20. Directory.CreateDirectory(GetGenerateDirectory());
  21. //File path
  22. string objFilePath = GetGenerateDirectory() + "/" + terrain.name + ".obj";
  23. //Save OBJ file
  24. StreamWriter sw = new StreamWriter(objFilePath);
  25. try
  26. {
  27. sw.WriteLine(strOBJ);
  28. }
  29. catch (System.Exception err)
  30. {
  31. Debug.LogError("Houston, we have a problem: " + err.Message);
  32. }
  33. sw.Close();
  34. //Refresh asset database
  35. AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
  36. //Load OBJ mesh
  37. gameObject.AddComponent<MeshFilter>().sharedMesh = (Mesh)AssetDatabase.LoadAssetAtPath(objFilePath, typeof(Mesh));
  38. gameObject.AddComponent<MeshRenderer>().sharedMaterial = new Material(Shader.Find("Diffuse"));
  39. }
  40. string GetGenerateDirectory()
  41. {
  42. return "Assets/Terrain Obj files/" + terrain.name;
  43. }
  44. }
  45. #endif