Search code examples
unity-game-enginenavmesh

Unity NavMesh path reverse


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();
    }
}

Solution

  • 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;