Daniel Lip
Daniel Lip

Reputation: 11325

How can I update a List only when needed in the Update at run time?

At the top :

public List<Vector3> lineRendererPositions = new List<Vector3>();

Then a method :

Vector3[] GetLinePointsInWorldSpace()
    {
        var positions = new Vector3[lineRenderer.positionCount];
        //Get the positions which are shown in the inspector 
        lineRenderer.GetPositions(positions);


        //the points returned are in world space
        return positions;
    }

Then in the Update :

private void Update()
    {
        lineRendererPositions.AddRange(GetLinePointsInWorldSpace());
    }

The problem is the Listi s getting bigger and bigger so the game get laggy and laggy. I could add a line before to make a new instance for the List :

private void Update()
        {
            lineRendererPositions = new List<Vector3>();
            lineRendererPositions.AddRange(GetLinePointsInWorldSpace());
        }

but I'm not sure this is a good way to Update the List. I want that when it's getting the positions from the GetLinePointsInWorldSpace if they are not the same as in the lineRendererPositions List then Update (AddRange).

or maybe doing it with new instance is fine enough ?

Upvotes: 2

Views: 123

Answers (2)

bmoglu
bmoglu

Reputation: 59

The problem does not seem so obvious. This usage looks very wasteful then you should ask yourself these questions.

  1. When do you need to update list?
  2. What do you need to update list after doing?

Upvotes: 0

Grizzlly
Grizzlly

Reputation: 596

The game is getting laggier because every frame you are adding the LinePoints to the current list. This rapidly increases memory usage. Add lineRendererPositions.Clear() before AddRange().

This will be fine. You don't have to do checks as the complexity is O(n) in both cases.

Upvotes: 2

Related Questions