导出NavMesh并保存为obj文件

作者:追风剑情 发布于:2018-3-18 16:08 分类:Unity3d

本文转自: http://blog.csdn.net/huutu/article/details/52672505

一、新建一个场景并烘焙好导航网格

7777.png

11111.png

隐藏掉障碍物效果

22222.png

代码: Unity2017

//本代码转自 http://blog.csdn.net/huutu/article/details/52672505

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEditor.AI;

public class ToolsEditor {

	[MenuItem("Tools/Export NavMesh")]
	public static void ExportNavMesh()
	{
		Debug.Log("Export NavMesh");  

		//Unity2017 API
		UnityEngine.AI.NavMeshTriangulation navMeshTriangulation = UnityEngine.AI.NavMesh.CalculateTriangulation();  
		string sceneName = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene ().name;

		//新建文件  
		string savePath = Application.dataPath + "/" + sceneName + "_NavMesh.obj";  
		StreamWriter sw = new StreamWriter(savePath);

		//顶点  
		for (int i=0;i<navMeshTriangulation.vertices.Length;i++)  
		{  
			sw.WriteLine("v  "+ navMeshTriangulation.vertices[i].x+" "+ navMeshTriangulation.vertices[i].y+" "+ navMeshTriangulation.vertices[i].z);  
		}  

		sw.WriteLine("g navmesh");//组名称

		//索引  
		for (int i = 0; i < navMeshTriangulation.indices.Length;)  
		{
			//obj文件中顶点索引是从1开始
			sw.WriteLine("f " + (navMeshTriangulation.indices[i]+1) + " " + (navMeshTriangulation.indices[i+1]+1) + " " + (navMeshTriangulation.indices[i+2]+1));
			i = i + 3;  
		}  

		sw.Flush();
		sw.Close();

		AssetDatabase.Refresh (ImportAssetOptions.ForceUpdate);

		Debug.Log (string.Format("Verts:{0}  Tris:{1}", navMeshTriangulation.vertices.Length, navMeshTriangulation.indices.Length/3));
		Debug.Log(savePath);
		Debug.Log("ExportNavMesh Success");  
	}
}

打印信息

66666.png

保存后的obj文件在Unity Project窗口中的显示

4444.png

把Scene1_NavMesh.obj的prefab拖到一个新场景中查看网格显示

333333.png

为了确保obj文件是正确的,我们再导入Autodesk FBX Review软件中查看

555555.png

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号