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

Unity 2018.1超64k顶点网格使用问题:32位索引缓冲失效

问题分析与解决方案

你遇到的这个情况是Unity 2018.1版本对32位索引缓冲的支持细节问题——虽然官方宣称支持,但Mesh默认仍然使用16位索引缓冲,而16位索引的最大值是65535。当你的网格顶点数超过这个值时(比如512×512=262144个顶点),索引值会被截断为低16位,导致大量顶点索引错乱,最终出现只显示1/4区域、三角面错误的问题。

256×256的网格刚好是65536个顶点,刚好踩过16位的阈值,可能Unity在这个临界值做了临时兼容处理,所以能正常显示,但这并不是稳定的状态。

解决步骤

只需要在创建Mesh后,手动将其索引格式设置为32位即可,具体修改如下:

修改后的完整代码示例

int nVertices = nx * ny;
Vector3[] vertices = new Vector3[nVertices];
Color[] colors = new Color[nVertices];

for(int i = 0; i < nx; i++) {
    float x = i * w / (nx - 1);
    for (int j = 0; j < ny; j++) {
        float y = j * h / (ny - 1);
        int vindex = i * ny + j;
        vertices[vindex] = new Vector3(x, y, 0);
        float colorx = Mathf.Sin(x) / 2 + 0.5f;
        float colory = Mathf.Cos(y) / 2 + 0.5f;
        colors[vindex] = new Color(0, 0, 0, colorx * colory);
    }
}

List<int> triangles = new List<int>();
for (int i = 1; i < nx; i++) {
    for (int j = 1; j < ny; j++) {
        int vindex1 = (i - 1) * ny + (j - 1);
        int vindex2 = (i - 1) * ny + j;
        int vindex3 = i * ny + (j - 1);
        int vindex4 = i * ny + j;
        triangles.Add(vindex1);
        triangles.Add(vindex2);
        triangles.Add(vindex3);
        triangles.Add(vindex4);
        triangles.Add(vindex3);
        triangles.Add(vindex2);
    }
}

Mesh mesh = new Mesh();
// 关键:设置为32位索引格式
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.SetVertices(vertices.ToList<Vector3>());
mesh.SetIndices(triangles.ToArray(), MeshTopology.Triangles, 0);
mesh.SetColors(colors.ToList<Color>());

补充说明

  • 这行设置代码一定要在SetIndices之前执行,确保Mesh在接收索引数据时使用正确的格式。
  • 注意:部分老旧的移动端GPU可能不支持32位索引缓冲,如果你的项目需要兼容这类设备,可能需要考虑拆分网格(将大网格拆分为多个顶点数不超过65535的子网格)。
  • 你的Shader不需要额外修改,只要Mesh的索引格式正确,Shader就能正常处理顶点数据。

效果对比

正常显示的256×256网格:
正常显示的256×256网格

显示异常的512×512网格(修改前):
显示异常的512×512网格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:12:37