How to clear LineRenderer path to redraw the line?

batuman picture batuman · Dec 26, 2017 · Viewed 10k times · Source

I have a LineRenderer path to show the path of the GolfBall. Please see in the image, maroon colour path.

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);
}

The path is drawn using the points in pts[] array.

In repeating the display, I need to clear the old path to redraw the same path again. How can I clear the old path?

Answer

Programmer picture Programmer · Dec 26, 2017

There is no clear function for LineRenderer and you do not need to clear it in order to redraw it. Also, LineRenderer don't need to be re-drawn manually. This is handle by Unity.

If your goal is to reset old vertex positions you set to it, simply set the LineRenderer's vertex count to 0. You can do this with the SetVertexCount(0) function or positionCount variable. Note that SetVertexCount is now deprecated.

This should remove all the lines you set to the LineRenderer:

LineRenderer.positionCount = 0;

Extension method for this:

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

Now, you can call lineRenderer.Reset() to reset all the previous positions/path you set to it.