C# Unity将地形(Terrain)导出成obj文件

2024-01-06 17:36

本文主要是介绍C# Unity将地形(Terrain)导出成obj文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

C# Unity将地形(Terrain)导出成obj文件

从其他地方搬运过来的,只能到出obj模型,不能导出贴图

using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using System;enum SaveFormat { Triangles, Quads }
enum SaveResolution { Full, Half, Quarter, Eighth, Sixteenth }class ExportTerrain : EditorWindow
{SaveFormat saveFormat = SaveFormat.Triangles;SaveResolution saveResolution = SaveResolution.Half;static TerrainData terrain;static Vector3 terrainPos;int tCount ;int counter ;int totalCount ;[MenuItem ("Terrain/Export To Obj...")]static void Init () {terrain = null;Terrain terrainObject = Selection.activeObject as Terrain;if (!terrainObject){terrainObject = Terrain.activeTerrain;}if (terrainObject){terrain = terrainObject.terrainData;terrainPos = terrainObject.transform.position;}EditorWindow.GetWindow(typeof(ExportTerrain), false, "MyWindow", true).Show();}void OnGUI () {if (!terrain){GUILayout.Label("No terrain found");if (GUILayout.Button("Cancel")){EditorWindow.GetWindow(typeof(ExportTerrain), false, "MyWindow", true).Close();}return;}saveFormat = (SaveFormat)EditorGUILayout.EnumPopup("Export Format", saveFormat);saveResolution = (SaveResolution)EditorGUILayout.EnumPopup("Resolution", saveResolution);if (GUILayout.Button("Export")){Export();}}void Export () {String fileName = EditorUtility.SaveFilePanel("Export .obj file", "", "Terrain", "obj");int w = terrain.heightmapWidth;int h = terrain.heightmapHeight;Vector3 meshScale = terrain.size;float tRes = Mathf.Pow(2, System.Convert.ToInt32(saveResolution));meshScale =new Vector3(meshScale.x / (w - 1) * tRes, meshScale.y, meshScale.z / (h - 1) * tRes);Vector2 uvScale = new Vector2(1.0f / (w - 1), 1.0f / (h - 1));float[,] tData = terrain.GetHeights(0, 0, w, h);w = (int)((w - 1) / tRes) + 1;h = (int)((h - 1) / tRes) + 1;Vector3[] tVertices = new Vector3[w * h];Vector2[] tUV = new Vector2[w * h];int[] tPolys;if (saveFormat == SaveFormat.Triangles){tPolys = new int[(w - 1) * (h - 1) * 6];}else{tPolys = new int[(w - 1) * (h - 1) * 4];}// Build vertices and UVsfor (int y = 0; y < h; y++){for (int x = 0; x < w; x++){tVertices[y * w + x] = Vector3.Scale(meshScale, new Vector3(x, tData[x * (int)tRes, y * (int)tRes], y)) + terrainPos;tUV[y * w + x] = Vector2.Scale(new Vector2(x * tRes, y * tRes), uvScale);}}var index = 0;if (saveFormat == SaveFormat.Triangles){// Build triangle indices: 3 indices into vertex array for each trianglefor (int y = 0; y < h - 1; y++){for (int x = 0; x < w - 1; x++){// For each grid cell output two trianglestPolys[index++] = (y * w) + x;tPolys[index++] = ((y + 1) * w) + x;tPolys[index++] = (y * w) + x + 1;tPolys[index++] = ((y + 1) * w) + x;tPolys[index++] = ((y + 1) * w) + x + 1;tPolys[index++] = (y * w) + x + 1;}}}else{// Build quad indices: 4 indices into vertex array for each quadfor (int y = 0; y < h - 1; y++){for (int x = 0; x < w - 1; x++){// For each grid cell output one quadtPolys[index++] = (y * w) + x;tPolys[index++] = ((y + 1) * w) + x;tPolys[index++] = ((y + 1) * w) + x + 1;tPolys[index++] = (y * w) + x + 1;}}}// Export to .objStreamWriter sw=null;try{sw=new StreamWriter(fileName);sw.WriteLine("# Unity terrain OBJ File");// Write verticesStringBuilder sb;System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");counter = tCount = 0;totalCount = (tVertices.Length * 2 + (saveFormat == SaveFormat.Triangles ? tPolys.Length / 3 : tPolys.Length / 4)) / 1000;for (int i = 0; i < tVertices.Length; i++){UpdateProgress();sb = new StringBuilder("v ", 20);// StringBuilder stuff is done this way because it's faster than using the "{0} {1} {2}"etc. format// Which is important when you're exporting huge terrains.sb.Append(tVertices[i].x.ToString()).Append(" ").Append(tVertices[i].y.ToString()).Append(" ").Append(tVertices[i].z.ToString());sw.WriteLine(sb);}// Write UVsfor (int i = 0; i < tUV.Length; i++){UpdateProgress();sb =new StringBuilder("vt ", 22);sb.Append(tUV[i].x.ToString()).Append(" ").Append(tUV[i].y.ToString());sw.WriteLine(sb);}if (saveFormat == SaveFormat.Triangles){// Write trianglesfor (int i = 0; i < tPolys.Length; i += 3){UpdateProgress();sb =new StringBuilder("f ", 43);sb.Append(tPolys[i] + 1).Append("/").Append(tPolys[i] + 1).Append(" ").Append(tPolys[i + 1] + 1).Append("/").Append(tPolys[i + 1] + 1).Append(" ").Append(tPolys[i + 2] + 1).Append("/").Append(tPolys[i + 2] + 1);sw.WriteLine(sb);}}else{// Write quadsfor (int i = 0; i < tPolys.Length; i += 4){UpdateProgress();sb =new StringBuilder("f ", 57);sb.Append(tPolys[i] + 1).Append("/").Append(tPolys[i] + 1).Append(" ").Append(tPolys[i + 1] + 1).Append("/").Append(tPolys[i + 1] + 1).Append(" ").Append(tPolys[i + 2] + 1).Append("/").Append(tPolys[i + 2] + 1).Append(" ").Append(tPolys[i + 3] + 1).Append("/").Append(tPolys[i + 3] + 1);sw.WriteLine(sb);}}}catch (Exception err){Debug.Log("Error saving file: " + err.Message);}if(sw!=null)sw.Close();terrain = null;EditorUtility.ClearProgressBar();EditorWindow.GetWindow(typeof(ExportTerrain), false, "MyWindow", true).Close();}void UpdateProgress () {if (counter++ == 1000){counter = 0;EditorUtility.DisplayProgressBar("Saving...", "", Mathf.InverseLerp(0, totalCount, ++tCount));}}
}

在这里插入图片描述

这篇关于C# Unity将地形(Terrain)导出成obj文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/577089

相关文章

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

用命令行的方式启动.netcore webapi

用命令行的方式启动.netcore web项目 进入指定的项目文件夹,比如我发布后的代码放在下面文件夹中 在此地址栏中输入“cmd”,打开命令提示符,进入到发布代码目录 命令行启动.netcore项目的命令为:  dotnet 项目启动文件.dll --urls="http://*:对外端口" --ip="本机ip" --port=项目内部端口 例: dotnet Imagine.M

C# dateTimePicker 显示年月日,时分秒

dateTimePicker默认只显示日期,如果需要显示年月日,时分秒,只需要以下两步: 1.dateTimePicker1.Format = DateTimePickerFormat.Time 2.dateTimePicker1.CustomFormat = yyyy-MM-dd HH:mm:ss Tips:  a. dateTimePicker1.ShowUpDown = t

C#关闭指定时间段的Excel进程的方法

private DateTime beforeTime;            //Excel启动之前时间          private DateTime afterTime;               //Excel启动之后时间          //举例          beforeTime = DateTime.Now;          Excel.Applicat

C# 防止按钮botton重复“点击”的方法

在使用C#的按钮控件的时候,经常我们想如果出现了多次点击的时候只让其在执行的时候只响应一次。这个时候很多人可能会想到使用Enable=false, 但是实际情况是还是会被多次触发,因为C#采用的是消息队列机制,这个时候我们只需要在Enable = true 之前加一句 Application.DoEvents();就能达到防止重复点击的问题。 private void btnGenerateSh

C# double[] 和Matlab数组MWArray[]转换

C# double[] 转换成MWArray[], 直接赋值就行             MWNumericArray[] ma = new MWNumericArray[4];             double[] dT = new double[] { 0 };             double[] dT1 = new double[] { 0,2 };

C# Hash算法之MD5、SHA

MD5我们用的还是比较多的,一般用来加密存储密码。但是现在很多人觉MD5可能不太安全了,所以都用上了SHA256等来做加密(虽然我觉得都差不多,MD5还是能玩)。 还是跟上一篇说的一样,当一个算法的复杂度提高的同时肯定会带来效率的降低,所以SHA和MD5比较起来的话,SHA更安全,MD5更高效。 由于HASH算法的不可逆性,所以我认为MD5和SHA主要还是应用在字符串的"加密"上。 由于

MySQL使用mysqldump导出数据

mysql mysqldump只导出表结构或只导出数据的实现方法 备份数据库: #mysqldump 数据库名 >数据库备份名 #mysqldump -A -u用户名 -p密码 数据库名>数据库备份名 #mysqldump -d -A --add-drop-table -uroot -p >xxx.sql 1.导出结构不导出数据 mysqldump --opt -d 数据库名 -u

一步一步将PlantUML类图导出为自定义格式的XMI文件

一步一步将PlantUML类图导出为自定义格式的XMI文件 说明: 首次发表日期:2024-09-08PlantUML官网: https://plantuml.com/zh/PlantUML命令行文档: https://plantuml.com/zh/command-line#6a26f548831e6a8cPlantUML XMI文档: https://plantuml.com/zh/xmi