- Home /
Make object move backwards/reverse on array of waypoints
I have a gameobject that follows waypoints in the order of their index in the array. The object can move follow all the waypoints, and it can do a loop where it goes from the last point in the array to the first one. What I'm trying to do is create an option that lets the object move in reverse. For example, moving from point 3 to point 2, or moving from the first index in the array to the last point. The script looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Patrol : MonoBehaviour
{
public float speed;
public Transform[] waypoints;
public bool isLooping;
public bool isReverse;
float waitTime = 0.3f;
int index = 0;
void Update()
{
if(index < waypoints.Length)
{
transform.position = Vector3.MoveTowards(transform.position, waypoints[index].position, speed * Time.deltaTime);
Debug.Log(index);
if (Vector3.Distance(transform.position, waypoints[index].position) < 0.2f)
{
if (waitTime <= 0)
{
index++;
}
else if (isReverse)
{
index--;
if (index == 0)
{
index = waypoints.Length;
}
}
else
{
waitTime -= Time.deltaTime;
}
}
}
else if(isLooping)
{
index = 0;
}
else if(isLooping && isReverse)
{
index = waypoints.Length;
}
else
{
return;
}
}
}
Whenever the isReverse bool is marked true in the inspector, the object only moves to the first point in the array and then stops moving. This is the error that shows up when it happens:
IndexOutOfRangeException: Index was outside the bounds of the array.
Patrol.Update () (at Assets/Scripts/Patrol.cs:20)
When isLooping is marked true and isReverse is marked false, the object continues the loop. If anyone can tell me how to get the object to move in reverese it'll be really appreciated ^^