Unity读取CSV文件生成迷宫
Unity利用C#的文件流读入文件生成迷宫
1.首先我们编写一个CSV文件,储存我们的迷宫数据
打开Sublime Text编写一个迷宫的文件,保存为UTF_8格式,不然Unity无法找到此文件。
2.打开Unity,在Assets下创建Resource文件夹
3.将我们保存好的文件复制到Resources文件夹下
4.编写生成迷宫的脚本Map.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Map : MonoBehaviour {
void Start () {
BuildMap();
}
void Update () {
}
void BuildMap()
{
TextAsset textAsset = (TextAsset)Resources.Load("Map");
string[] map_row_string = textAsset.text.Trim().Split('\n');
int map_row_max_cells = 0;
List<List<string>> map_Collections = new List<List<string>>();
for(int i=0;i<map_row_string.Length;i++) //读取每一行的数据
{
List<string> map_row = new List<string>(map_row_string[i].Split(','));
if (map_row_max_cells < map_row.Count)
{
map_row_max_cells = map_row.Count;
}
map_Collections.Add(map_row);
}
//生成一个刚好放Cube的Plane
GameObject map_Plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
map_Plane.transform.position = new Vector3(0, 0, 0);
//求其原始大小
float map_Plane_original_x_size = map_Plane.GetComponent<MeshFilter>().mesh.bounds.size.x;
float map_Plane_original_z_size = map_Plane.GetComponent<MeshFilter>().mesh.bounds.size.z;
//缩放这个Map到所需大小,刚好和二维表匹配
float map_Plane_x = map_row_max_cells / map_Plane_original_x_size;
float map_Plane_z = map_Collections.Count / map_Plane_original_z_size;
map_Plane.transform.localScale = new Vector3(map_Plane_x, 1, map_Plane_z);
//在Plane上放Cube
for(int i = 0; i < map_Collections.Count; i++)
{
for(int j = 0; j < map_Collections[i].Count; j++)
{
int cube_num = int.Parse(map_Collections[i][j]);
for(int k = 0; k < cube_num; k++)
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = new Vector3(-(map_row_max_cells / 2) + i, (float)0.5 + k, -(map_Collections.Count / 2) + j);
}
}
}
}
}
5.在Unity场景中新建一个空物体GameObject,用来挂载脚本
6.运行游戏得到我们想要的迷宫效果