When the loop flag is set to true it’s continuing moving between the waypoints nonsotp.
The problem is when the flag loop is set to false then it stop at the last waypoint but then also give exception : ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
The index is keep raising in the Move function.
I’m not sure how to solve it when the loop flag is false.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Waypoints : MonoBehaviour
{
public float speed;
public bool go = false;
public bool moveToFirstPositionOnStart = false;
public List<Transform> positions;
public bool loop = true;
private int index = 0;
// Start is called before the first frame update
void Start()
{
if (moveToFirstPositionOnStart == true)
{
transform.position = positions[index].position;
}
}
// Update is called once per frame
void Update()
{
if (go == true)
{
Move();
}
}
void Move()
{
transform.position = Vector3.MoveTowards(transform.position,
positions[index].position,
speed * Time.deltaTime);
float distance = Vector3.Distance(transform.position, positions[index].position);
if (distance < 0.01f)
{
positions[index].GetComponent<Renderer>().material.color = Color.red;
index += 1;
}
if (index == positions.Count && loop)
{
index = 0;
}
}
}
>Solution :
Use the following to stop entering Move at the end of your waypoint sequence depending on if loop is disabled or not:
if (index == positions.Count)
{
index = 0;
go = loop;
}