1. 程式人生 > >二維數組以及地圖高度數據存儲方式

二維數組以及地圖高度數據存儲方式

定義 tle left lin ase texture 以及 text 高度

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();

二維數組以及地圖高度數據存儲方式