I’m creating a list of Vector3s to store the positions that I want to set a line renderer’s elements equal to. (Because LineRenderers are stupid and I don’t have enough control of them). I’m getting an error for not being in the Lists range, but I can’t find out why. The two errors take me to very similar lines of code. I’m adding a new Vector and then accessing it so I’m not sure why the index is out of range. If you can’t recall the error I’m referring to I’ll paste it below.
ArgumentOutOfRangeException: Argument is out of range.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent (typeof(LineRenderer))]
public class Electricity : MonoBehaviour
{
//Public Variables
public Vector3 startPoint;
public Vector3 endPoint;
public int vertexCount = 12;
public float maxDepth = 8f;
public float positionRange = 0.15f;
public float radius = 1f;
public float moveSpeed = 5f;
public float newPositionDelay = 0.5f;
public float fadeSpeed = 10f;
public LineRenderer lineRenderer;
//Private Variables
private Color color = Color.white;
private Vector2 midpoint;
private List<Vector3> vertexPositions = new List<Vector3>();
private List<Vector3> goalPositions = new List<Vector3>();
void Start ()
{
lineRenderer = this.GetComponent<LineRenderer>();
InvokeRepeating("GenerateVertexPositions", 0, newPositionDelay);
}
void Update ()
{
for(int i = 1; i < (vertexCount - 1); i++)
{
//The first error takes me to the line below
vertexPositions[i] = Vector3.Lerp(vertexPositions[i], goalPositions[i], moveSpeed * Time.deltaTime);
lineRenderer.SetPosition(i, vertexPositions[i]);
}
lineRenderer.SetColors(color, color);
color.a -= fadeSpeed * Time.deltaTime;
if(color.a <= 0)
color.a += 255;
}
void GenerateVertexPositions ()
{
for(int i = 1; i < (vertexCount - 1); i++)
{
if(vertexPositions.Count < vertexCount)
{
vertexPositions.Add(new Vector3());
lineRenderer.SetVertexCount(vertexPositions.Count);
}
float vertexDepth = ((float)i * (maxDepth) / (float)(vertexCount - 1));
//The seconderror takes me to the line below
goalPositions[i] = new Vector3(Random.Range(-positionRange, positionRange), Random.Range(-positionRange, positionRange), vertexDepth);
}
lineRenderer.SetColors(color, color);
color.a -= fadeSpeed * Time.deltaTime;
if(color.a <= 0)
color.a += 255;
vertexPositions[0] = startPoint;
vertexPositions[vertexCount - 1] = endPoint;
lineRenderer.SetPosition(0, vertexPositions[0]);
lineRenderer.SetPosition(vertexCount - 1, vertexPositions[vertexPositions.Count]);
}
}