user12014800
user12014800

Reputation:

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

Upvotes: 0

Views: 892

Answers (1)

Horothenic
Horothenic

Reputation: 678

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;

Upvotes: 0

Related Questions