Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

How do I use this to get random points on a navmesh?

Discussion in 'Scripting' started by omablak, Mar 2, 2020.

  1. omablak

    omablak

    Joined:
    Feb 10, 2020
    Posts:
    10
    I want to spawn animals on random points on our navmesh. First I though maybe I could get the hitbox / collider for the navmesh and then iterate upwards unti the hitbox of the animal collides with the navmesh and then spawn it there. But I found this code that I might be able to use: https://gist.github.com/IJEMIN/f2510a85b1aaf3517da1af7a6f9f1ed3

    However, I don't know how to use my navmesh on this method since it has no argument for the navmesh. How can I use this method? Is there a better way to do it?.

    thanks
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,525
    I believe you use it like this:
    Code (CSharp):
    1. var randomDestination = GetRandomPoint(transform.position, 100);
    2. agent.SetDestination(randomDestination);
    "100" should be a public variable so that you can tweak it in the inspector. It defines how far from the agents current position the random point should be.

    "agent" is a NavMeshAgent component. Declare it and assign the NavMeshAgent component to it.
     
    omablak likes this.
  3. omablak

    omablak

    Joined:
    Feb 10, 2020
    Posts:
    10
    thanks
     
  4. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,479
    you can also use NavMesh.SamplePosition with your random position, to get the closest point that is on the navmesh
     
unityunity