EditorObjExporter.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*
  2. Based on ObjExporter.cs, this "wrapper" lets you export to .OBJ directly from the editor menu.
  3. This should be put in your "Editor"-folder. Use by selecting the objects you want to export, and select
  4. the appropriate menu item from "Custom->Export". Exported models are put in a folder called
  5. "ExportedObj" in the root of your Unity-project. Textures should also be copied and placed in the
  6. same folder.
  7. N.B. there may be a bug so if the custom option doesn't come up refer to this thread http://answers.unity3d.com/questions/317951/how-to-use-editorobjexporter-obj-saving-script-fro.html
  8. Updated for Unity 5.3
  9. */
  10. using UnityEngine;
  11. using UnityEditor;
  12. using UnityEditor.SceneManagement;
  13. using System.Collections;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Text;
  17. using System;
  18. struct ObjMaterial
  19. {
  20. public string name;
  21. public string textureName;
  22. }
  23. public class EditorObjExporter : ScriptableObject
  24. {
  25. private static int vertexOffset = 0;
  26. private static int normalOffset = 0;
  27. private static int uvOffset = 0;
  28. //User should probably be able to change this. It is currently left as an excercise for
  29. //the reader.
  30. private static string targetFolder = "ExportedObj";
  31. private static string MeshToString(MeshFilter mf, Dictionary<string, ObjMaterial> materialList)
  32. {
  33. Mesh m = mf.sharedMesh;
  34. Material[] mats = mf.GetComponent<Renderer>().sharedMaterials;
  35. StringBuilder sb = new StringBuilder();
  36. sb.Append("g ").Append(mf.name).Append("\n");
  37. foreach (Vector3 lv in m.vertices)
  38. {
  39. Vector3 wv = mf.transform.TransformPoint(lv);
  40. //This is sort of ugly - inverting x-component since we're in
  41. //a different coordinate system than "everyone" is "used to".
  42. sb.Append(string.Format("v {0} {1} {2}\n", -wv.x, wv.y, wv.z));
  43. }
  44. sb.Append("\n");
  45. foreach (Vector3 lv in m.normals)
  46. {
  47. Vector3 wv = mf.transform.TransformDirection(lv);
  48. sb.Append(string.Format("vn {0} {1} {2}\n", -wv.x, wv.y, wv.z));
  49. }
  50. sb.Append("\n");
  51. foreach (Vector3 v in m.uv)
  52. {
  53. sb.Append(string.Format("vt {0} {1}\n", v.x, v.y));
  54. }
  55. for (int material = 0; material < m.subMeshCount; material++)
  56. {
  57. sb.Append("\n");
  58. sb.Append("usemtl ").Append(mats[material].name).Append("\n");
  59. sb.Append("usemap ").Append(mats[material].name).Append("\n");
  60. //See if this material is already in the materiallist.
  61. try
  62. {
  63. ObjMaterial objMaterial = new ObjMaterial();
  64. objMaterial.name = mats[material].name;
  65. if (mats[material].mainTexture)
  66. objMaterial.textureName = AssetDatabase.GetAssetPath(mats[material].mainTexture);
  67. else
  68. objMaterial.textureName = null;
  69. materialList.Add(objMaterial.name, objMaterial);
  70. }
  71. catch (ArgumentException)
  72. {
  73. //Already in the dictionary
  74. }
  75. int[] triangles = m.GetTriangles(material);
  76. for (int i = 0; i < triangles.Length; i += 3)
  77. {
  78. //Because we inverted the x-component, we also needed to alter the triangle winding.
  79. sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n",
  80. triangles[i] + 1 + vertexOffset, triangles[i + 1] + 1 + normalOffset, triangles[i + 2] + 1 + uvOffset));
  81. }
  82. }
  83. vertexOffset += m.vertices.Length;
  84. normalOffset += m.normals.Length;
  85. uvOffset += m.uv.Length;
  86. return sb.ToString();
  87. }
  88. private static void Clear()
  89. {
  90. vertexOffset = 0;
  91. normalOffset = 0;
  92. uvOffset = 0;
  93. }
  94. private static Dictionary<string, ObjMaterial> PrepareFileWrite()
  95. {
  96. Clear();
  97. return new Dictionary<string, ObjMaterial>();
  98. }
  99. private static void MaterialsToFile(Dictionary<string, ObjMaterial> materialList, string folder, string filename)
  100. {
  101. using (StreamWriter sw = new StreamWriter(folder + "_" + filename + ".mtl"))
  102. {
  103. foreach (KeyValuePair<string, ObjMaterial> kvp in materialList)
  104. {
  105. sw.Write("\n");
  106. sw.Write("newmtl {0}\n", kvp.Key);
  107. sw.Write("Ka 0.6 0.6 0.6\n");
  108. sw.Write("Kd 0.6 0.6 0.6\n");
  109. sw.Write("Ks 0.9 0.9 0.9\n");
  110. sw.Write("d 1.0\n");
  111. sw.Write("Ns 0.0\n");
  112. sw.Write("illum 2\n");
  113. if (kvp.Value.textureName != null)
  114. {
  115. string destinationFile = kvp.Value.textureName;
  116. int stripIndex = destinationFile.LastIndexOf(Path.PathSeparator);
  117. if (stripIndex >= 0)
  118. destinationFile = destinationFile.Substring(stripIndex + 1).Trim();
  119. string relativeFile = destinationFile;
  120. destinationFile = folder + "_" + destinationFile;
  121. Debug.Log("Copying texture from " + kvp.Value.textureName + " to " + destinationFile);
  122. try
  123. {
  124. //Copy the source file
  125. File.Copy(kvp.Value.textureName, destinationFile);
  126. }
  127. catch
  128. {
  129. }
  130. sw.Write("map_Kd {0}", relativeFile);
  131. }
  132. sw.Write("\n\n\n");
  133. }
  134. }
  135. }
  136. public static void MeshToFile(MeshFilter mf, string folder, string filename)
  137. {
  138. Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();
  139. using (StreamWriter sw = new StreamWriter("Assets/ExportedObj/"+filename + ".obj"))
  140. {
  141. //sw.Write("mtllib ./" + filename + ".mtl\n");
  142. sw.Write(MeshToString(mf, materialList));
  143. sw.Close();
  144. }
  145. //MaterialsToFile(materialList, folder, filename);
  146. }
  147. private static void MeshesToFile(MeshFilter[] mf, string folder, string filename)
  148. {
  149. Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();
  150. using (StreamWriter sw = new StreamWriter(folder + Path.PathSeparator + filename + ".obj"))
  151. {
  152. sw.Write("mtllib ./" + filename + ".mtl\n");
  153. for (int i = 0; i < mf.Length; i++)
  154. {
  155. sw.Write(MeshToString(mf[i], materialList));
  156. }
  157. }
  158. MaterialsToFile(materialList, folder, filename);
  159. }
  160. private static bool CreateTargetFolder()
  161. {
  162. try
  163. {
  164. string exportPath = Application.dataPath +"/"+ targetFolder;
  165. if (!System.IO.Directory.Exists(exportPath))
  166. System.IO.Directory.CreateDirectory(exportPath);
  167. }
  168. catch
  169. {
  170. EditorUtility.DisplayDialog("Error!", "Failed to create target folder!", "");
  171. return false;
  172. }
  173. return true;
  174. }
  175. //[MenuItem("Custom/Export/Export all MeshFilters in selection to separate OBJs")]
  176. //static void ExportSelectionToSeparate()
  177. //{
  178. // if (!CreateTargetFolder())
  179. // return;
  180. // Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
  181. // if (selection.Length == 0)
  182. // {
  183. // EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
  184. // return;
  185. // }
  186. // int exportedObjects = 0;
  187. // for (int i = 0; i < selection.Length; i++)
  188. // {
  189. // Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
  190. // for (int m = 0; m < meshfilter.Length; m++)
  191. // {
  192. // exportedObjects++;
  193. // MeshToFile((MeshFilter)meshfilter[m], targetFolder, selection[i].name + "_" + i + "_" + m);
  194. // }
  195. // }
  196. // if (exportedObjects > 0)
  197. // EditorUtility.DisplayDialog("Objects exported", "Exported " + exportedObjects + " objects", "");
  198. // else
  199. // EditorUtility.DisplayDialog("Objects not exported", "Make sure at least some of your selected objects have mesh filters!", "");
  200. //}
  201. //[MenuItem("Custom/Export/Export each selected to single OBJ")]
  202. //static void ExportEachSelectionToSingle()
  203. //{
  204. // if (!CreateTargetFolder())
  205. // return;
  206. // Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
  207. // if (selection.Length == 0)
  208. // {
  209. // EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
  210. // return;
  211. // }
  212. // int exportedObjects = 0;
  213. // for (int i = 0; i < selection.Length; i++)
  214. // {
  215. // Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
  216. // MeshFilter[] mf = new MeshFilter[meshfilter.Length];
  217. // for (int m = 0; m < meshfilter.Length; m++)
  218. // {
  219. // exportedObjects++;
  220. // mf[m] = (MeshFilter)meshfilter[m];
  221. // }
  222. // MeshesToFile(mf, targetFolder, selection[i].name + "_" + i);
  223. // }
  224. // if (exportedObjects > 0)
  225. // {
  226. // EditorUtility.DisplayDialog("Objects exported", "Exported " + exportedObjects + " objects", "");
  227. // }
  228. // else
  229. // EditorUtility.DisplayDialog("Objects not exported", "Make sure at least some of your selected objects have mesh filters!", "");
  230. //}
  231. [MenuItem("RO_Tool/Mesh/合并成预设")]
  232. static void CombineToPrefab()
  233. {
  234. if (!CreateTargetFolder())
  235. return;
  236. GameObject selectGo = Selection.activeGameObject;
  237. if (selectGo == null)
  238. {
  239. EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
  240. return;
  241. }
  242. GameObject go = null;
  243. PrefabInstanceStatus status = PrefabInstanceStatus.Disconnected;
  244. if (PrefabUtility.GetPrefabAssetType(selectGo) == PrefabAssetType.Regular)
  245. {
  246. status = PrefabUtility.GetPrefabInstanceStatus(selectGo);
  247. if (status == PrefabInstanceStatus.NotAPrefab)
  248. {
  249. go = GameObject.Instantiate(selectGo);
  250. }
  251. else
  252. {
  253. go = selectGo;
  254. }
  255. }
  256. else
  257. {
  258. go = selectGo as GameObject;
  259. }
  260. if (go == null) return;
  261. MeshRenderer mSMR = go.GetComponent<MeshRenderer>();
  262. if (mSMR != null)
  263. UnityEngine.Object.DestroyImmediate(mSMR);
  264. MeshFilter meshFilter = go.GetComponent<MeshFilter>();
  265. if (meshFilter != null)
  266. UnityEngine.Object.DestroyImmediate(meshFilter);
  267. List<CombineInstance> combineInstances = new List<CombineInstance>();
  268. MeshRenderer[] smrList = go.GetComponentsInChildren<MeshRenderer>();
  269. Material mat = null;
  270. for (int idx = 0; idx < smrList.Length; idx++)
  271. {
  272. MeshRenderer smr = smrList[idx];
  273. if (mat == null)
  274. mat = smr.sharedMaterial;
  275. MeshFilter mf = smr.GetComponent<MeshFilter>();
  276. CombineInstance ci = new CombineInstance();
  277. ci.mesh = mf.sharedMesh;
  278. ci.transform = mf.transform.localToWorldMatrix;
  279. combineInstances.Add(ci);
  280. }
  281. mSMR = go.AddComponent<MeshRenderer>();
  282. meshFilter = go.AddComponent<MeshFilter>();
  283. mSMR.sharedMaterial = mat;
  284. meshFilter.sharedMesh = new Mesh();
  285. meshFilter.sharedMesh.CombineMeshes(combineInstances.ToArray(), true);
  286. MeshToFile(meshFilter, targetFolder, selectGo.name);
  287. UnityEngine.Object.DestroyImmediate(mSMR);
  288. UnityEngine.Object.DestroyImmediate(meshFilter);
  289. if (status == PrefabInstanceStatus.NotAPrefab)
  290. {
  291. UnityEngine.Object.DestroyImmediate(go);
  292. }
  293. AssetDatabase.Refresh();
  294. string objFilePath = "Assets/ExportedObj/" + selectGo.name + ".obj";
  295. string objPrefabFilePath = "Assets/ExportedObj/" + selectGo.name + ".prefab";
  296. UnityEngine.GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(objFilePath);
  297. GameObject objInst = GameObject.Instantiate(obj);
  298. MeshRenderer r = objInst.GetComponentInChildren<MeshRenderer>();
  299. r.sharedMaterial = mat;
  300. PrefabUtility.SaveAsPrefabAsset(objInst, objPrefabFilePath);
  301. UnityEngine.Object.DestroyImmediate(objInst);
  302. }
  303. [MenuItem("RO_Tool/Mesh/合并mesh")]
  304. static void CombineToMesh()
  305. {
  306. if (!CreateTargetFolder())
  307. return;
  308. GameObject selectGo = Selection.activeGameObject;
  309. if (selectGo == null)
  310. {
  311. EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
  312. return;
  313. }
  314. GameObject go = null;
  315. PrefabInstanceStatus status = PrefabInstanceStatus.Disconnected;
  316. if (PrefabUtility.GetPrefabAssetType(selectGo) == PrefabAssetType.Regular)
  317. {
  318. status = PrefabUtility.GetPrefabInstanceStatus(selectGo);
  319. if (status == PrefabInstanceStatus.NotAPrefab)
  320. {
  321. go = GameObject.Instantiate(selectGo);
  322. }
  323. else
  324. {
  325. go = selectGo;
  326. }
  327. }
  328. else
  329. {
  330. go = selectGo as GameObject;
  331. }
  332. if (go == null) return;
  333. MeshRenderer mSMR = go.GetComponent<MeshRenderer>();
  334. if (mSMR != null)
  335. UnityEngine.Object.DestroyImmediate(mSMR);
  336. MeshFilter meshFilter = go.GetComponent<MeshFilter>();
  337. if (meshFilter != null)
  338. UnityEngine.Object.DestroyImmediate(meshFilter);
  339. List<CombineInstance> combineInstances = new List<CombineInstance>();
  340. MeshRenderer[] smrList = go.GetComponentsInChildren<MeshRenderer>();
  341. Material mat = null;
  342. for (int idx = 0; idx < smrList.Length; idx++)
  343. {
  344. MeshRenderer smr = smrList[idx];
  345. if (mat == null)
  346. mat = smr.sharedMaterial;
  347. MeshFilter mf = smr.GetComponent<MeshFilter>();
  348. CombineInstance ci = new CombineInstance();
  349. ci.mesh = mf.sharedMesh;
  350. ci.transform = mf.transform.localToWorldMatrix;
  351. combineInstances.Add(ci);
  352. }
  353. mSMR = go.AddComponent<MeshRenderer>();
  354. meshFilter = go.AddComponent<MeshFilter>();
  355. mSMR.sharedMaterial = mat;
  356. meshFilter.sharedMesh = new Mesh();
  357. meshFilter.sharedMesh.CombineMeshes(combineInstances.ToArray(), true,true,true);
  358. MeshToFile(meshFilter, targetFolder, selectGo.name);
  359. UnityEngine.Object.DestroyImmediate(mSMR);
  360. UnityEngine.Object.DestroyImmediate(meshFilter);
  361. if (status == PrefabInstanceStatus.NotAPrefab)
  362. {
  363. UnityEngine.Object.DestroyImmediate(go);
  364. }
  365. AssetDatabase.Refresh();
  366. }
  367. [MenuItem("Assets/ExportMesh")]
  368. static void TestMesh()
  369. {
  370. if (!CreateTargetFolder())
  371. return;
  372. UnityEngine.Object obj = Selection.activeObject;
  373. if (obj == null || PrefabUtility.GetPrefabAssetType(obj) != PrefabAssetType.Model) return;
  374. GameObject objGo = obj as GameObject;
  375. MeshFilter mf = objGo.GetComponent<MeshFilter>();
  376. Vector3 offset = mf.sharedMesh.bounds.center;
  377. offset.y = 0;
  378. if (mf != null)
  379. {
  380. List<Vector3> newVertices = new List<Vector3>();
  381. Mesh mesh = mf.sharedMesh;
  382. for (int idx = 0; idx < mesh.vertices.Length; idx++)
  383. {
  384. Vector3 newPos = mesh.vertices[idx] - offset;
  385. newVertices.Add(newPos);
  386. }
  387. mesh.SetVertices(newVertices);
  388. mf.sharedMesh = mesh;
  389. MeshToFile(mf, targetFolder, obj.name);
  390. Debug.Log("Completed");
  391. }
  392. }
  393. [MenuItem("Custom/Export/Export whole selection to single OBJ")]
  394. static void ExportWholeSelectionToSingle()
  395. {
  396. if (!CreateTargetFolder())
  397. return;
  398. Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
  399. if (selection.Length == 0)
  400. {
  401. EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
  402. return;
  403. }
  404. int exportedObjects = 0;
  405. ArrayList mfList = new ArrayList();
  406. for (int i = 0; i < selection.Length; i++)
  407. {
  408. Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
  409. for (int m = 0; m < meshfilter.Length; m++)
  410. {
  411. exportedObjects++;
  412. mfList.Add(meshfilter[m]);
  413. }
  414. }
  415. if (exportedObjects > 0)
  416. {
  417. MeshFilter[] mf = new MeshFilter[mfList.Count];
  418. for (int i = 0; i < mfList.Count; i++)
  419. {
  420. mf[i] = (MeshFilter)mfList[i];
  421. }
  422. string filename = EditorSceneManager.GetActiveScene().name + "_" + exportedObjects;
  423. int stripIndex = filename.LastIndexOf(Path.PathSeparator);
  424. if (stripIndex >= 0)
  425. filename = filename.Substring(stripIndex + 1).Trim();
  426. MeshesToFile(mf, targetFolder, filename);
  427. EditorUtility.DisplayDialog("Objects exported", "Exported " + exportedObjects + " objects to " + filename, "");
  428. }
  429. else
  430. EditorUtility.DisplayDialog("Objects not exported", "Make sure at least some of your selected objects have mesh filters!", "");
  431. }
  432. }