繁体   English   中英

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

[英]How to get elements in Jagged array in C# (UNITY 3d)

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM