如何在c# (UNITY 3d)中获得锯齿数组中的元素

本文关键字:数组 元素 3d UNITY | 更新日期: 2023-09-27 18:12:15

我创建了一个3d int数组

public int[,,]  npcState =  new int[,,] {
    {
        {0,0}
    },{
        {1,9,1},{1,0,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    },{
        {1,1,1},{10,10}
    },{
        {8,0},{0,0},{0,0},{0,0}
    },{
        {10,7},{1,1,1},{1,1,1},{1,1,1},{1,1,1}
    },{
        {2,2,2}
    },{
        {1,1,1} ,{1,1,1}
    },{
        {8,11},{0,0},{0,0},{0,0},{0,0}
    },{
        {0,1,1},{1,1,1}
    }
};

我的问题是

1。)如何在运行时赋值

2。)如何使用循环

检查数组的每一行和列
for(int i =0 ; i < firstDimensionalLength ; i ++){
  for(int j =0 ; j < secondDimensionalLength; j ++){
     for(int k =0 ; k < thirdDimensionalLength; k ++){
// print (npcState[i,j,k]); 
   }
  }
}

如果它的长度对所有维度都是恒定的,则很容易找到元素。但是如果它是动态的如何在特定位置找到每个元素

如何在c# (UNITY 3d)中获得锯齿数组中的元素

编辑:根据评论者的建议,我正在添加多维数组声明的编译版本:

public int[,,] npcState =  new int[,,] {
    {
       {2,2,2},{1,1,1},{1,1,1}
    },{
        {1,9,1},{1,0,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    },{
       {2,2,2},{1,1,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    },{
        {2,2,2},{1,1,1},{1,1,1}
    }
};

如果你真的想使用for循环,那么你可以使用GetLength()方法访问维度的长度:

var firstDimensionalLength = npcState.GetLength(0);
var secondDimensionalLength = npcState.GetLength(1);
var thirdDimensionalLength = npcState.GetLength(2);

如果您只想扫描整个数组,请尝试使用foreach:

foreach (int item in npcState) {
  // print (item); 
  if (SomeCondition(item)) {
    ...
  }  
}

请注意,循环不依赖于数组的尺寸(对于1d, 2d, 3d等数组都是一样的)

编辑:如果你想要项目的位置(即i, j, k索引),你必须把

// In many cases you can put 0 instead of `npcState.GetLowerBound()` since 
// arrays are zero based by default
for (int i = npcState.GetLowerBound(0); i <= npcState.GetUpperBound(0); i++)
  for (int j = npcState.GetLowerBound(1); j <= npcState.GetUpperBound(1); ++j)
    for (int k = npcState.GetLowerBound(2); k <= npcState.GetUpperBound(2); ++k) {
      int item = npcState[i, j, k];
      ...
    }

Edit 2:由于问题已被编辑,并且N-D数组已变成锯齿一个,解决方案也应该被更改:

  int[][][] npcState = new int[][][] {
    new int[][] {
      new int[] { 0, 0 } },
    new int[][] {
      new int[] { 1, 9, 1},
      new int[] { 1, 0, 1},
      new int[] { 1, 1, 1}, },
    new int[][] {
      new int[] { 2, 2, 2},
      new int[] { 1, 1, 1},
      new int[] { 1, 1, 1}, }, 
    // ...
  };
 // Array of array of array can be just flatten twice
 foreach (var item in npcState.SelectMany(line => line.SelectMany(row => row))) {
   ...
 }

保存位置的循环将是

 for (int i = 0; i < npcState.Length; ++i) 
   for (int j = 0; j < npcState[i].Length; ++j) 
     for (int k = 0; k < npcState[i][j].Length; ++k) {
       int item = npcState[i][j][k];
       ...   
     }