1.二维数组定义
int[,] arr = new int[len0, len1];
定义一个len0行,len1列的二维数组,这里的len0,len1指的是GetLength(index)
int[,] arr=new int[2,3];//2行3列的数组 Console.Out.WriteLine(arr.GetLength(0)+","+arr.GetLength(1));//输出2,3 int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 } }; Console.Out.WriteLine(arr.GetLength(0)+","+arr.GetLength(1));//输出2,3
2.遍历方式
int[,] arr = new int[len0, len1];
for (int i = 0; i < len0; i++)
for (int j = 0; j < len1; j++)
Console.WriteLine(arr[i, j]);
arr[i,j]代表第i行,第j列的某值:
例子:
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine(arr[1, 2]);//输出 6,第1行,第2列(起点为0)
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 } }; for (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++) { Console.WriteLine(arr[i, j]); } //输出1,2,3,4,5,6,
3.地图高度数组存储
如定义一个width=5,length=4的地图
数组应该定义如下:(经测试,terrain内置的高度数据也是这样存的)
int length = 4; int width = 5; int[,] arr = new int[length, width]; for (int i = 0; i < length; i++) for (int j = 0; j < width; j++) { arr[i, j] = 该点高度; }
4.高度图输出
输出高度图有点区别,高度图的存储是不同的,统一按以下去写入:
Texture2D tex = new Texture2D(width, length); for (int i = 0; i < width; i++) for (int j = 0; j < length; j++) { tex.SetPixel(i, j, new Color(arr[j, i], arr[j, i],arr[j, i])); } string str = Application.dataPath + "/normal_test.png"; byte[] byt = tex.EncodeToPNG(); File.WriteAllBytes(str, byt); AssetDatabase.Refresh();