I assume you were getting NullReferenceException
because the list was not being initialized when it was private.
However, when the list was public, Unity by default serializes public variables to be visible in the inspector, which consequently initializes the list.
This can be fixed by simply initializing the private list to equal new List<Vector3>()
on the same line it is declared.
Change this:
private List<Vector3> wayPointsPositions;
To this:
private List<Vector3> wayPointsPositions = new List<Vector3>();
This is what your new code should look like:
private LineRenderer lineRenderer;
private GameObject[] wayPointsObject;
private List<Vector3> wayPointsPositions = new List<Vector3>();
void Start()
{
lineRenderer = GetComponent<LineRenderer>();
wayPointsObject = GameObject.FindGameObjectsWithTag("WayPoints");
for (int i = 0; i < wayPointsObject.Length; i++)
{
wayPointsPositions.Add(wayPointsObject[i].transform.position);
}
lineRenderer.positionCount = wayPointsPositions.Count;
lineRenderer.SetPositions(wayPointsPositions.ToArray());
}
Hope this fixes your issue :)
SIDE NOTE - IF YOU WANT TO IMPROVE EFFICIENCY OF YOUR CODE:
Your code can be rewritten without using a list at all, as arrays can be used instead:
The below code has also renamed wayPointsObject
to wayPointObjects
, wayPointsPositions
to wayPointPositions
, and the tag "WayPoints"
to "WayPoint"
, as these names make more sense.
private LineRenderer lineRenderer;
private GameObject[] wayPointObjects;
private Vector3[] wayPointPositions;
void Start()
{
lineRenderer = GetComponent<LineRenderer>();
wayPointObjects = GameObject.FindGameObjectsWithTag("WayPoint");
wayPointPositions = new Vector3[wayPointObjects.Length];
for (int i = 0; i < wayPointObjects.Length; i++)
{
wayPointPositions[i] = wayPointObjects[i].transform.position;
}
lineRenderer.positionCount = wayPointPositions.Length;
lineRenderer.SetPositions(wayPointPositions);
}