如何在负索引 C#(UNITY) 处启动数组



嗨,我是 C# 编程的新手,我只是想问是否有办法将索引启动到负 1?

这是我的代码

string[,] table = new string[104, 15];
int xIndex = -1;
int yIndex = 0;
if(table.GetLength(0) < xIndex){
break;
}
if (result.Equals(newPrevious) || result.Equals("A") && yIndex <  table.GetLength(1))
{
yIndex += 1;
table[xIndex, yIndex] = result;
}
else
{
xIndex += 1;
yIndex = 0;
table [xIndex, yIndex] = result;
}
previous = result ;
if (!result.Equals("A"))
{
newPrevious = previous;
}

这里给了我一个错误

if (result.Equals(newPrevious) || result.Equals("A") && yIndex <  table.GetLength(1))
{
yIndex += 1;
table[xIndex, yIndex] = result;   //<---- ERROR HERE
}
索引

超出范围异常:数组索引超出范围。

编辑

我会解释我在做什么.我正在为我的游戏创建一个记分牌,这个xIndexyIndex作为我的对象在我的记分牌内的位置,就像这样

例如,我的string[] strData = {"A ,B ,B ,B ,C ,C ,C ,B ,B ,A ,B ,C ,A ,C "};上有这个值

它会给我一个Exception错误

但是如果我把string[] strData改成这个string[] strData = {"B ,B ,B ,B ,C ,C ,C ,B ,B ,A ,B ,C ,A ,C "};

它不会给我一个异常错误。

编辑 2

这是我的整个代码

string[,] table = new string[104, 15];
int xIndex = -1;
int yIndex = 0;
string newPrevious = "placeholder";
//C = BLUE, B = RED, A = GREEN
string[] strData = {"A  ,C  ,C  ,C  ,C  ,C  ,C  ,B  ,B  ,A  ,B  ,C  ,A  ,C  "};
//conditions
string[] scoreBoard = new string[]
{"C  ", "B  ", "A  ",
"C B","B C" };
string OriginalData = "";

void Start(){
StartCoroutine ("Win_Log");
}
IEnumerator Win_Log(){
yield return new WaitForEndOfFrame ();
for (int i = 0; i < strData.Length; i++) {
OriginalData += strData [i];
OriginalData += ",";
}
string[] newNewData = OriginalData.Split (',');
string result = "";
string previous = "";

foreach (string newStrData in newNewData) {
Debug.Log ("This is the data : " + newStrData);
GameObject o = Instantiate (prefab_gameobject) as GameObject;
o.transform.SetParent (pos_big_road);
o.transform.localScale = Vector3.one;
img = (RawImage)o.GetComponent<RawImage> ();
//check the length so that it won't throw an exception
if (newStrData.Length > 1) {
//get only the first letter of the value A,B,C
result = newStrData.Substring (0, 1);
} 
else {
result = "";
}

#region BIG ROAD
if(table.GetLength(0) < xIndex){
break;
}
if (result.Equals(newPrevious) || result.Equals("A") && yIndex <  table.GetLength(1))
{
yIndex += 1;
table[xIndex, yIndex] = result;
}
else if (result.Equals("A"))
{
xIndex += 1;
table[xIndex, yIndex] = result;
}
else
{
xIndex += 1;
yIndex = 0;
table [xIndex, yIndex] = result;
}
previous = result ;
if (!result.Equals("A"))
{
newPrevious = previous;
}

这是我想要期待的输出

预期输出

但是,如果将first string value更改为B or C则不会引发异常错误。

正如您在图像链接中看到的那样,如果值超过 7,它将移动到 x 轴,但仍然与 y 轴相同。

不,数组索引从 0 开始。

我不确定尝试使用负索引有什么意义,但您可以尝试通过考虑 0 您的(减去您的最低值)来模拟它。

最新更新