Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

I need help with moving to random waypoints on a navmesh

Discussion in 'Navigation' started by Vandius, May 18, 2019.

  1. Vandius

    Vandius

    Joined:
    Oct 4, 2016
    Posts:
    2
    I've been stuck for HOURS! How do I use Random.Range with this code to make it so NPCs go to random waypoints? This code works perfect other than the NPCs only stay on one route.

    using UnityEngine;
    using UnityEngine.AI;
    using System.Collections;

    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();
    }
    }[/code]
     
    Last edited: May 18, 2019
  2. Vandius

    Vandius

    Joined:
    Oct 4, 2016
    Posts:
    2
    I really wanna use this code and not something bloated, so how would I add Random.Range to this?
     
  3. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    491
    new positions can simply be calculated with new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max))
    Min and Max should be set to the minimum and maximum bounds of the world. Keep in mind you can get positions that aren't on the Navmesh, so to be sure all your points can be reached, use NavMeshAgent.SamplePosition(the calculated position).