public List<Vector3> destinations = new List<Vector3>();
    public int numberOfDestionations;
    public float moveSpeed = 5f;
    public bool loop = false;
    public bool moveBack = false;
    public Text textCounter;

    private Coroutine movementCoroutine;
    private bool pause = false;
    private bool coroutineRunning = false;
    private Vector3 startPosition;
    private int countDestionations;

    private void Start()
        for (int i = 0; i < numberOfDestionations; i++)
            destinations.Add(new Vector3(UnityEngine.Random.Range(-300, 25), -1f, 0));//25, -1f, 0);
            if(i > 0)
                Gizmos.DrawLine(destinations[i], destinations[i + 1]);

I'm trying to use gizmos but getting exception :

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

On line 33 :

Gizmos.DrawLine(destinations[i], destinations[i + 1]);

I want that while it's creating the vectors draw lines from the current created vector destination and the next one. A line from index 0 to index 1 to index 2 and so on. So when running the game I will see a net of all the lines connected between the vectors destinations.

  • \$\begingroup\$ Hint: think of what the second point in the line would be when i = numberOfDestinations - 1 \$\endgroup\$
    – DMGregory
    Commented Feb 12, 2021 at 2:05

1 Answer 1


Try something like this instead. You can still initialize your destinations list in Start, but draw it in OnDrawGizmos, and make sure your index never reaches the list's current .Count.

void OnDrawGizmos() {
    // Skip drawing if we don't have at least two points to connect.
    if (destinations == null || destinations.Count < 2)

    for (int i = 1; i < destinations.Count; i++) {
        Gizmos.DrawLine(destinations[i - 1], destinations[i]);
  • \$\begingroup\$ For some reason it's never going inside the OnDrawGizmos. I used a break point and it's never get to it when running the game. \$\endgroup\$
    – Daniel Lip
    Commented Feb 12, 2021 at 2:19
  • \$\begingroup\$ I'm not able to reproduce that. It's called just fine on any MonoBehaviour I've ever used this with in the editor. Check your spelling, and that you didn't accidentally nest the function inside another one. \$\endgroup\$
    – DMGregory
    Commented Feb 12, 2021 at 2:25
  • \$\begingroup\$ @DanielJacksonville If it's not working, then it's likely that destinations is null or has less than two entries. \$\endgroup\$
    – Kevin
    Commented Feb 12, 2021 at 3:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .