<分区>
您好,我是 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
}
IndexOutOfRangeException: Array index is out of range.
编辑
我会解释我在做什么。我正在为我的游戏创建一个记分牌,这个 xIndex
和 yIndex
像这样用作我的对象在我的记分牌中的位置
例如我的 string[] strData = {"A ,B ,B ,B ,C ,C ,C ,B ,B ,A ,B ,C ,A ,C "} ;
它会给我一个异常
错误
但是如果我将我的 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;
}
这是我想要的输出
但如果将第一个字符串值
更改为B或C
,则不会抛出异常错误。
正如您在图像链接中看到的那样,如果值超过 7,它将移动到 x 轴,但仍与 y 轴相同。