如何在C#中获取Jagged数组中的元素(UNITY 3d)

时间:2016-10-10 08:52:39

标签: c# arrays unity3d

我创建了一个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]); 
   }
  }
}

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

2 个答案:

答案 0 :(得分:1)

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

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

Source

答案 1 :(得分:1)

如果您只想扫描整个阵列,请尝试使用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];
      ...
    }

编辑2 :由于问题已被编辑且 ND 数组已变为锯齿状,因此解决方案也应该已更改:

  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];
       ...   
     }