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

Unity C#中使用Line Renderer实现多线条的二维数组写法求助

用Line Renderer绘制多条线的二维数组正确写法

首先明确:Unity的LineRenderer.SetPositions()方法需要传入一维Vector3数组,所以得区分C#里两种多维数组的用法——交错数组(Vector3[][])更适配这个场景,因为每条线的点数可灵活调整,且能直接给SetPositions传参;多维数组(Vector3[,])则需要额外转换。

正确代码示例

1. 初始化资源

// 假设要画3条线,每条线有10个点
int lineCount = 3;
int pointCountPerLine = 10;

// 初始化交错数组:第一维存线条索引,第二维存对应线条的点集合
Vector3[][] positions = new Vector3[lineCount][];
for (int z = 0; z < lineCount; z++)
{
    positions[z] = new Vector3[pointCountPerLine];
    // 给每条线的起始点赋初始值,比如按X轴偏移区分不同线条
    positions[z][0] = new Vector3(z * 2, 0, 0);
}

// 初始化LineRenderer数组:可从场景获取或动态创建
LineRenderer[] lineRenderers = new LineRenderer[lineCount];
for (int z = 0; z < lineCount; z++)
{
    GameObject lineObj = new GameObject($"Line_{z}");
    lineRenderers[z] = lineObj.AddComponent<LineRenderer>();
    // 设置线条基础属性
    lineRenderers[z].startWidth = 0.1f;
    lineRenderers[z].endWidth = 0.1f;
}

2. 更新点并绑定到LineRenderer

比如更新第z条线的第n+1个点:

float Bxpe = 0.5f;
float Bype = 0.2f;
float Bzpe = 0f;

// 操作第z条线的第n+1个点,注意数组索引格式
positions[z][n + 1] = new Vector3(
    positions[z][n].x + Bxpe,
    positions[z][n].y + Bype,
    positions[z][n].z + Bzpe
);

// 直接把第z条线的点数组传给对应LineRenderer
lineRenderers[z].SetPositions(positions[z]);

若使用多维数组(Vector3[,])的写法

如果一定要用多维数组,需要先把对应行的点转成一维数组再传参:

// 初始化多维数组
Vector3[,] positions = new Vector3[lineCount, pointCountPerLine];
// 初始化点的代码略

// 更新点
positions[z, n + 1] = new Vector3(
    positions[z, n].x + Bxpe,
    positions[z, n].y + Bype,
    positions[z, n].z + Bzpe
);

// 提取第z行的点转成一维数组
Vector3[] linePoints = new Vector3[pointCountPerLine];
for (int i = 0; i < pointCountPerLine; i++)
{
    linePoints[i] = positions[z, i];
}

// 传给LineRenderer
lineRenderers[z].SetPositions(linePoints);

你原有代码的问题

  1. 数组索引格式错误:交错数组要用[z][n],[z,n]是多维数组的写法
  2. 点引用错误:更新点时应该取第z条线的第n个点(positions[z][n].x),而非positions[n].x
  3. SetPositions传参错误:交错数组直接传对应线条的一维数组positions[z]即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:42:05