[英]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.