You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity绘制线条时触发索引越界异常的原因排查

解决Unity绘制线条时的索引越界异常

看起来你在Unity里绘制网格顶点组成的三角形线条时遇到了索引越界的问题,我来帮你排查并解决这个问题:

问题根源

你的代码逻辑是每3个顶点为一组绘制三角形的三条边,但循环的终止条件有问题:你用了for (int i = 0; i < newVertices.Length; i++),但实际控制顶点索引的是counter变量,每次循环counter +=3。当counter的值接近数组末尾时,counter +1或者counter +2会超出newVertices数组的最大索引(数组索引从0开始,最大索引是newVertices.Length -1),这就触发了索引越界异常。

举个简单例子:如果你的顶点数组长度是10,当counter等于9时,counter +1就是10,这已经超出了数组的有效索引范围(最大是9),直接抛出异常。

修复后的代码

我们需要修改循环条件,确保counter +2始终小于数组长度,这样访问newVertices[counter]、newVertices[counter+1]、newVertices[counter+2]时都不会越界。同时删掉没用的i变量,让代码更清晰:

方案一:使用while循环

private void Start() 
{
    Mesh meshprefab = meshPrefab.GetComponent<MeshFilter>().sharedMesh;
    newVertices = meshprefab.vertices;
    
    int counter = 0;
    // 确保counter+2不超过数组最大索引
    while (counter <= newVertices.Length - 3) 
    {
        DrawLine(newVertices[counter], newVertices[counter + 1], Color.red);
        DrawLine(newVertices[counter + 1], newVertices[counter + 2], Color.red);
        DrawLine(newVertices[counter + 2], newVertices[counter], Color.red);
        counter += 3;
    }
}

方案二:使用for循环(更规范)

private void Start() 
{
    Mesh meshprefab = meshPrefab.GetComponent<MeshFilter>().sharedMesh;
    newVertices = meshprefab.vertices;
    
    // 每次步进3,循环到数组长度减3的位置
    for (int counter = 0; counter <= newVertices.Length - 3; counter += 3) 
    {
        DrawLine(newVertices[counter], newVertices[counter + 1], Color.red);
        DrawLine(newVertices[counter + 1], newVertices[counter + 2], Color.red);
        DrawLine(newVertices[counter + 2], newVertices[counter], Color.red);
    }
}

额外提示

  • 原代码中的i变量是冗余的,声明后没有被使用,删掉它可以避免代码混淆。
  • 如果你的网格顶点总数不是3的倍数,最后剩余的1个或2个顶点会被跳过,这是合理的——因为你要绘制的是三角形线条,不足3个顶点无法组成完整的三角形。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:18:24