2

I want to make a simple script, that guides a NavMesh agent to various waypoints. I am new to Unity so I don't know some basic functions yet, which is instead typed in pseudo code.

using UnityEngine;
using UnityEngine.AI;

public class Path_left_blue : MonoBehaviour {

    private Transform target;
    private int wavepointindex = 0;
    public NavMeshAgent agent;

    void Start () {
        target = Waypoints_blue_left.waypoints[0];
    }

    void Update () {
        //Set destination to waypoint
        Vector3 dir = target.position;
        agent.setDestination(dir);

        if (agent is within a close range/touching target waypoint)

            //Remove object if at the last waypoint
            if (wavepointindex == Waypoints_blue_left.waypoints.Length)
                Destroy(gameObject);

            wavepointindex++;
            target = Waypoints_blue_left.waypoints[wavepointindex];

    }
}

1 Answer 1

3

void Update() function called each frame. So you need a function that check if the agent arrives to point, set the new destination to it.

I changed your code to this:

using UnityEngine;
using UnityEngine.AI;

public class Path_left_blue : MonoBehaviour 
{
    private Transform target;
    private int wavepointindex = -1;
    public NavMeshAgent agent;

    void Start () 
    {
        EnemyTowardNextPos();
    }

    void Update () 
    {
        // agent is within a close range/touching target waypoint
        if (!agent.pathPending && agent.remainingDistance < 0.5f)
        {
            EnemyTowardNextPos();
        }
    }

    void EnemyTowardNextPos ()
    {
        if(wavepointindex == Waypoints_blue_left.waypoints.Length - 1)
        {
            Destroy(gameObject);
        }
        else
        {
            // set destination to waypoint
            wavepointindex++;
            target = Waypoints_blue_left.waypoints[wavepointindex];
            agent.SetDestination(target);
        }
    }
}

EnemyTowardNextPos() function only called when agent arrives to current point.

I hope it helps you

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.