0

I need to reverse this script used to make a game object to patrol between some transforms. I need the object to navigate sequentially from point (1, 2, 3, 4, 5) and when it reaches the end of the array it reverse the order of the array itself so that it will navigate back (5, 4, 3, 2 ,1).

using UnityEngine;
using UnityEngine.AI;
public class Patrol : MonoBehaviour
{

    public Transform[] points;
    private int destPoint = 0;
    private NavMeshAgent agent;


    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        agent.autoBraking = false;
        GotoNextPoint();
    }


    void GotoNextPoint()
    {
        if (points.Length == 0)
            return;

        agent.destination = points[destPoint].position;
        destPoint = (destPoint + 1) % points.Length;
    }


    void Update()
    {
        if (!agent.pathPending && agent.remainingDistance < 0.5f)
            GotoNextPoint();
    }
}
  • Turn your +1 "`(destPoint + 1)`" into a variable `(desPoint + x)`. Declare `x = 1;` then before assigning your agent.destination do `if (points.Length == 0) { x = x * -1}` – jiveturkey Jun 15 '20 at 13:23

1 Answers1

0

You should use Array.Reverse when reaching final point for easy implementation on your code.

Documentation here.

Add this code to the end of GoToNextPoint.

destPoint++;
if (destPoint >= points.Length)
{
    Array.Reverse(points);
    destPoint = 0;
}

And remove.

destPoint = (destPoint + 1) % points.Length;
Horothenic
  • 680
  • 6
  • 12
  • Thanks Horothenic, it works like a charm. Easy implementation. I suspected there was a "reverse" component to use but I wasn't able to make it work. –  Jun 15 '20 at 13:59
  • It is not efficient tho, it would be more efficient a variable that goes up and down on the same array, to avoid creating more arrays, but this works, the Reverse is not going to be triggered a lot on runtime anyway, – Horothenic Jun 16 '20 at 14:03
  • I thought `Array.Reverse` would already take the existing array "points" and just reverse it, without creating new ones. –  Jun 16 '20 at 19:13