【问题标题】:C# Array index is out of range but index is zeroC# 数组索引超出范围但索引为零
【发布时间】:2013-06-16 17:34:40
【问题描述】:
public int Laenge = 10;
public int Breite = 10;   
public Vector3[] new_Ver = new Vector3[300];
public Vector3[,] new_Ver_s = new Vector3[11,11];
public Vector2[] new_UV = new Vector2[300];
public Vector2[,] new_UV_s = new Vector2[11,11];


void Start () {
int n=0;
for(int l=0;l<=Laenge;l++)
    {
        for(int b=0;b<=Breite;b++)
        {
            if(b>1 || l<Laenge)
            {
                if(b%2 ==1)
                {
                    Debug.Log(l);Debug.Log(b);Debug.Log(n+"f");
                    new_Ver[n]=new_Ver_s[l,b]; //this is the line where it says theres a bug.
                    new_UV[n]=new_UV_s[l,b];
                    n++;
                }     
            }
        }   
    }

上面写着:

IndexOutOfRangeException: 数组索引超出范围

但调试说所有的 indizes 都是零。是因为元素是空的吗?我怎样才能轻松地把东西放在那里?如果我对二维数组做同样的事情,就没有问题。 我尝试了一些方法并将 new_Uv_s 替换为一个空的 vector3 变量。它仍然是同样的错误。'

【问题讨论】:

  • 您应该使用调试器并单步执行您的代码,以查看您在什么时候得到了异常。这可能会告诉你你的逻辑有什么问题。
  • 检查 new_Ver_s、new_UV 和 new_UV_s 数组的大小
  • 抱歉,忘记了。

标签: c# arrays unity3d


【解决方案1】:

您的代码注定要崩溃,因为您在每次迭代时增加 n,并且您可能有类似 50 次迭代 => 在某个时候 n 将超过 29 最后一次new_Ver 数组的索引。

为什么将其大小设置为 30?

如果你想要一些纬度,请使用 100。:)

【讨论】:

  • 是的,我必须将其更改为 300。但它甚至不做一个循环。
  • 您确定您的代码看起来正确吗?您应该真正使用 Visual Studio 提供的调试器。
  • 我将 debug.logs 放在任何地方,用于 l b 和 n 并且它始终为零,它只运行到我在代码中添加注释的地方。我想可能是因为数组是空的。
  • 你知道我可以寻找什么吗?
  • 我已经测试了你的代码,它运行良好,至少它不会崩溃和循环 54 次。您使用的是什么工具:Visual、CSC、MonoDevelop...
猜你喜欢
  • 2021-06-20
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多