protectedstaticvoidExportSelectionToSeparate(){if(!CreateTargetFolder())return;Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);if(selection.Length ==0){EditorUtility.DisplayDialog("No source object selected!","Please select one or more target objects","");return;}int exportedObjects =0;for(int i =0; i < selection.Length; i++){Component[] components = selection[i].GetComponentsInChildren(typeof(T));for(int m =0; m < components.Length; m++){exportedObjects++;MeshToFile((T)components[m], targetFolder, selection[i].name +"_"+ i +"_"+ m);}}if(exportedObjects >0)EditorUtility.DisplayDialog("Objects exported","Exported "+ exportedObjects +" objects","");elseEditorUtility.DisplayDialog("Objects not exported","Make sure at least some of your selected objects have mesh filters!","");}
protectedstaticstringMeshToString(Mesh mesh, Material[] materials,string name,Transform transform, Dictionary<string, ObjMaterial> materialList){StringBuilder sb =newStringBuilder();sb.Append("g ").Append(name).Append("\n");//數據起始foreach(Vector3 lv in mesh.vertices){//頂點數據循環輸入Vector3 wv = transform.TransformPoint(lv);//This is sort of ugly - inverting x-component since we're in//a different coordinate system than "everyone" is "used to".sb.Append(string.Format("v {0} {1} {2}\n",-wv.x, wv.y, wv.z));}sb.Append("\n");//空格foreach(Vector3 lv in mesh.normals){//法線數據循環輸入Vector3 wv = 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 mesh.uv){//UV數據循環輸入sb.Append(string.Format("vt {0} {1}\n", v.x, v.y));}for(int material =0; material < mesh.subMeshCount; material++){//材質數據循環輸入sb.Append("\n");//空格sb.Append("usemtl ").Append(materials[material].name).Append("\n");sb.Append("usemap ").Append(materials[material].name).Append("\n");try{//See if this material is already in the materiallist.看看這個字典是否已經在字典中ObjMaterial objMaterial =newObjMaterial{name = materials[material].name};if(materials[material].mainTexture)objMaterial.textureName = AssetDatabase.GetAssetPath(materials[material].mainTexture);//另一種方式EditorUtility.GetAssetPath(mats[material].mainTexture)elseobjMaterial.textureName =null;materialList.Add(objMaterial.name, objMaterial);}catch(ArgumentException){//已經在字典中//Already in the dictionary}int[] triangles = mesh.GetTriangles(material);for(int i =0; i < triangles.Length; i +=3){//Because we inverted the x-component, we also needed to alter the triangle winding.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 += mesh.vertices.Length;normalOffset += mesh.normals.Length;uvOffset += mesh.uv.Length;return sb.ToString();}
[MenuItem("Custom/Export Obj/MeshFilter/導出所有選擇的網格過濾器以分離的Obj形式")]//Export all MeshFilters in selection to separate ObjsprotectedstaticvoidExportSelectionToSeparate_MF(){ExportSelectionToSeparate();}