77 lines
2.8 KiB
C#
77 lines
2.8 KiB
C#
using UnityEngine;
|
||
using UnityEngine.AI;
|
||
using System.Text;
|
||
using System.IO;
|
||
using UnityEditor;
|
||
|
||
public static class NavMeshExporter
|
||
{
|
||
[MenuItem("Tools/Export NavMesh to Obj (Right-Handed 右手坐标系)")]
|
||
public static void ExportRight()
|
||
{
|
||
NavMeshTriangulation triangulatedNavMesh = NavMesh.CalculateTriangulation();
|
||
|
||
if (triangulatedNavMesh.vertices.Length == 0)
|
||
{
|
||
Debug.LogError("NavMesh is empty! Please bake it first.");
|
||
return;
|
||
}
|
||
|
||
StringBuilder sb = new StringBuilder();
|
||
sb.AppendLine("g NavMesh");
|
||
|
||
// ========== ✅ 修改点1:顶点坐标 转右手坐标系 (仅对Z轴取反,X/Y不变) ==========
|
||
foreach (Vector3 v in triangulatedNavMesh.vertices)
|
||
{
|
||
sb.Append($"v {v.x} {v.y} {-v.z}\n"); // 核心改动:-v.z
|
||
}
|
||
|
||
// ========== ✅ 修改点2:三角面绕序反转 (修正法线朝向,避免背面剔除) ==========
|
||
for (int i = 0; i < triangulatedNavMesh.indices.Length; i += 3)
|
||
{
|
||
// 原始顺序:i → i+1 → i+2
|
||
// 右手坐标系顺序:i+2 → i+1 → i 核心改动
|
||
sb.Append($"f {triangulatedNavMesh.indices[i + 2] + 1} {triangulatedNavMesh.indices[i + 1] + 1} {triangulatedNavMesh.indices[i] + 1}\n");
|
||
}
|
||
|
||
string path = Path.Combine(Application.dataPath, "NavMeshExport.obj");
|
||
File.WriteAllText(path, sb.ToString());
|
||
Debug.Log($"✅ 右手坐标系 NavMesh exported to: {path}");
|
||
AssetDatabase.Refresh();
|
||
}
|
||
|
||
|
||
//[MenuItem("Tools/Export NavMesh to Obj (Left-Handed 左手坐标系)")]
|
||
//public static void ExportLeft()
|
||
//{
|
||
// NavMeshTriangulation triangulatedNavMesh = NavMesh.CalculateTriangulation();
|
||
|
||
// if (triangulatedNavMesh.vertices.Length == 0)
|
||
// {
|
||
// Debug.LogError("NavMesh is empty! Please bake it first.");
|
||
// return;
|
||
// }
|
||
|
||
// StringBuilder sb = new StringBuilder();
|
||
// sb.AppendLine("g NavMesh");
|
||
|
||
// // 1. 写入顶点 (保持 Unity 原始坐标 v.x, v.y, v.z)
|
||
// foreach (Vector3 v in triangulatedNavMesh.vertices)
|
||
// {
|
||
// // 不取反 x
|
||
// sb.Append($"v {v.x} {v.y} {v.z}\n");
|
||
// }
|
||
|
||
// // 2. 写入面 (保持 Unity 原始绕序 i, i+1, i+2)
|
||
// for (int i = 0; i < triangulatedNavMesh.indices.Length; i += 3)
|
||
// {
|
||
// // 不交换顺序
|
||
// sb.Append($"f {triangulatedNavMesh.indices[i] + 1} {triangulatedNavMesh.indices[i + 1] + 1} {triangulatedNavMesh.indices[i + 2] + 1}\n");
|
||
// }
|
||
|
||
// string path = Path.Combine(Application.dataPath, "NavMeshExport.obj");
|
||
// File.WriteAllText(path, sb.ToString());
|
||
// Debug.Log($"NavMesh exported (Raw Unity Coords) to: {path}");
|
||
// AssetDatabase.Refresh();
|
||
//}
|
||
} |