Unity 3D游戏开发 - C#语法基础 | 数组之二维数组

二维数组基本语法

  • 声明+初始化
    数据类型[,]  数组名 = new 数据类型[行数,列数];
  • 赋值与取值
    • 赋值:   数组名[下标,下标] = 值;
    • 取值:   数组名[下标,下标];
  • 声明+初始化+赋值
    数据类型[,]  数组名 = new 数据类型[,]{
    
       {0,0,0,0,0,0,0,0,0,0},
       {1,1,1,1,1,1,1,1,1,1}
    
    };                  //每一行对应一个大括号.

二维数组的遍历

  • for循环嵌套
    数组名.GetLength(轴向下标);     //可以获得某个轴向的元素个数.
    
    
                int[,] intArray = new int[,]{
                    {1,2,3},
                    {11,22,33},
                    {111,222,333},
                    {1111,2222,3333}
                };
    
                for (int i = 0; i < intArray.GetLength(0); i++)
                {
                    for (int j = 0; j < intArray.GetLength(1); j++)
                    {
                        Console.Write(intArray[i, j] + "\t");
                    }
                    Console.WriteLine();
                }
    
                Console.ReadKey();

二维数组在游戏中的应用

  • 存储游戏地图
  • 练习:二维数组存储迷宫地图.
                int[,] gamesMap = new int[,]{
                    {1,1,0,1,1,1,1,0,1,1,1,1,1,1,1},
                    {1,0,0,0,0,0,1,0,0,0,0,0,1,1,1},
                    {1,1,0,0,0,0,0,0,1,0,0,0,0,1,1},
                    {1,1,0,0,0,0,1,0,0,0,0,0,0,1,1},
                    {1,1,1,0,0,1,0,0,0,0,0,0,0,0,1},
                    {1,0,0,0,0,1,0,0,1,0,1,1,1,1,1},
                    {1,0,0,0,0,0,1,0,0,0,0,0,1,1,1},
                    {1,1,1,1,1,1,1,1,1,1,1,0,1,1,1}
                };
    
                for (int i = 0; i < gamesMap.GetLength(0); i++)
                {
                    for(int j = 0; j < gamesMap.GetLength(1); j++)
                    {
                        if(gamesMap[i,j] == 1)
                        {
                            Console.Write("■");
                        }
                        if(gamesMap[i, j] == 0)
                        {
                            Console.Write("□");
                        }
                    }
                    Console.WriteLine();
                }
    
               Console.ReadKey();
    Unity 3D游戏开发 - C#语法基础 | 数组之二维数组_第1张图片​​​​​​​

你可能感兴趣的:(Unity 3D游戏开发 - C#语法基础 | 数组之二维数组)