如何清除 LineRenderer 的路径以重新绘制线条?

3
我有一个 LineRenderer 路径来展示高尔夫球的轨迹。请参考图片中的褐色路径。

enter image description here

private void createTrail()
{
    lineRenderer.SetColors(tracerColor, tracerColor);
    lineRenderer.SetVertexCount(maxVertexCount);
    for (int idx = 0; idx < (maxVertexCount - 2); idx++)
    {//Add another vertex to show ball's roll
        lineRenderer.SetPosition(idx, new Vector3((float)pts[idx * (int)positionSampling].z, (float)pts[idx * (int)positionSampling].y, (float)pts[idx * (int)positionSampling].x));
    }
    lineRenderer.SetPosition(maxVertexCount - 2, new Vector3((float)pts[goal - 1].z, (float)pts[goal - 1].y, (float)pts[goal - 1].x));
    lineRenderer.SetPosition(maxVertexCount - 1, transform.position);
}

路径是使用pts[]数组中的点绘制的。

在重复显示时,我需要清除旧路径以重新绘制相同的路径。如何清除旧路径?

1个回答

11
LineRenderer没有明确的功能,不需要清除它才能重新绘制。此外,LineRenderer不需要手动重新绘制,这由Unity来处理。
如果你的目标是重置之前设置的顶点位置,只需将LineRenderer的顶点数设置为0即可。你可以使用SetVertexCount(0)函数或positionCount变量来实现。注意,SetVertexCount现在已被弃用。
这应该会删除所有你设置到LineRenderer中的线条:
LineRenderer.positionCount = 0;

针对此扩展方法:

public static class ExtensionMethod
{
    public static void Reset(this LineRenderer lr)
    {
        lr.positionCount = 0;
    }
}

现在,您可以调用lineRenderer.Reset()来重置您之前设置的所有位置/路径。


1
我认为这个方法不起作用(至少在我的情况下是如此)。如果你想继续绘制,像SetVertexCount(0)一样只是将旧位置设置为0,它们仍然存在。所以如果你想再次绘制,你会发现新绘制的起始点有点随机,保留了旧点的参考。而且LineRenderer会得到更多的位置,新的和旧的,但最新的已经被设置为0了。 - Lotan
对Lotan的观点表示赞同:将positionCount设置为零会隐藏线条,但不会清除旧状态。GetPosition(pos)仍将返回旧值。 - nicb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接