此问题在此处已有答案:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?(5个答案)
7天前关闭。
我试图使网格渲染在Unity 3D,但代码应该工作,这里是它说:* 索引超出范围异常:索引超出数组的边界。网格生成器.CreateShape()(位于资产/网格生成器.cs:33)*网格生成器.Start()(位于资产/网格生成器.cs:22)
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class MeshGen : MonoBehaviour {
Mesh mesh;
Vector3[] vertices;
int[] triangles;
public int xSize = 20;
public int zSize = 20;
// Start is called before the first frame update
void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
CreateShape();
UpdateMesh();
}
void CreateShape()
{
vertices = new Vector3[(xSize * 1) * (zSize * 1)];
int i = 0;
for (int z = 0; z <= zSize; z++)
{
for (int x = 0; x <= xSize; x++)
{
vertices[i] = new Vector3(x, 0, z);
i++;
}
}
triangles = new int[xSize * zSize * 6];
int vert = 0;
int tris = 0;
for (int x = 0; x < xSize; x++)
{
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + xSize + 1;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + 1;
triangles[tris + 4] = vert + xSize + 1;
triangles[tris + 5] = vert + xSize + 2;
vert++;
tris += 6;
}
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
private void OnDrawGizmos()
{
if (vertices == null)
{return;}
for (int i = 0; i < vertices.Length; i++)
{
Gizmos.DrawSphere(vertices[i], .1f);
}
}
}
我试着修复它,试着在谷歌上搜索,我确保它是正确的。这是我得到的唯一错误。
1条答案
按热度按时间hgqdbh6s1#
让我们检查一下:
您可能应该切换到严格不等式
<
,而不是<=