Destroying a LineRenderer component and then adding it again at runtime

I have a global `var lineRenderer:LineRenderer` that is:

  • initiated in `Start()` via `lineRenderer = gameObject.AddComponent(LineRenderer);`
  • has its `setPosition()` populated with a bunch of coordinates - so it appears like a "drawn line" on a whiteboard

And then I want to erase the board - presumably, the way to do that is `Destroy()` ... so I tried `Destroy(lineRenderer);`

When I attempt to reinitiate it with `lineRenderer = gameObject.AddComponent(LineRenderer);`, I get errors like: "Can't add component 'Line Renderer' to lRenderer (name of game object) because such a component is already added to the game object!"

Subsequent lineRenderer.property assign's yield errors like: "Object reference not set to an instance of an object"

So, long description short, how do you ERASE the line from a lineRenderer, so that you can repopulate its setPosition? (Not sure if destroy is the right word..)

By reading the documentation, it looks like you want

GetComponent(LineRenderer).SetVertexCount(0)

Although I realize that I am replying to this post a couple of months later than necessary, perhaps I can help somebody anyway. This error exists in ordinary .NET apps. When I see this error, I fix the problem by inserting code similar to:

lineRender = new LineRenderer();

Hope this helps.

public LineRenderer lineRenderer;

Start()
{
lineRenderer = gameObject.GetComponent<LineRenderer>();
}

Update()
{
if (your desired conditions)
{
lineRenderer.SetVertexCount(0);
}

That seems to be working for me, hope this helps.

you can use
lineRenderer.positionCount = 0;

lineRenderer.SetVertexCount(0); is outdated.