Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. The Burst compiler has its own forum section now.
    Dismiss Notice
  3. 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

Get random positions (enemy spawn) inside an NavMesh

Discussion in 'Scripting' started by SimStm, Sep 28, 2015.

  1. SimStm


    May 24, 2013

    Well, I'm trying to make a "random enemy spawn" script, who will populate dynamically my scene based on the NavMesh generated by Unity (so the enemy will not spawn inside a building or an "off-limits" area).

    I've found some examples in Unity Answers but haven't got any good results yet. In the examples, they used a mix of Vector3 Random.Range vars and NavMesh.SamplePosition to get the approximated result (of the random value) in NavMesh, but here I get the same position every time (even randomizing between -1000 and 1000 or -100 and 100).

    Anyone have made something like that before and can bring me a light? :D

    Code (csharp):
    1. int layerMask = (1 << NavMesh.GetAreaFromName("Default"));
    2. var position = new Vector3(Random.Range(-50f, 50f), 0, Random.Range(-50f, 50f));
    3. NavMeshHit hit;
    4. NavMesh.SamplePosition(position, out hit, 50f, layerMask);
    5. Instantiate(ZombiePrefab, hit.position, new Quaternion(0, 0, 0, 0));


    EDIT: The first problem was solved. I just missed the "NavMesh LayerMask" ID and the "distance float" is lower than the min/max X and Z positions, so the hit.position returns an Infinity Vector3.

    Now I have another problem. Just see my post above.
    Last edited: Sep 29, 2015
  2. JamesLeeNZ


    Nov 15, 2011
    why don't you show us some code so we can tell you what you did wrong.
  3. SimStm


    May 24, 2013
    Ok, the code is now on first post and I've solved the first problem.

    The second problem is this:

    In my test area, I'm using a plane with the size 50x50. If I randomize the Vector3 using -50f by 50f everything will be fine, because the prefabs will be spawned randomly as it should.

    On another scene, I have, for example, a destroyed city with buildings, multiple roads, objects in the middle of the road (the objects are not that important) with the NavMesh areas with all kind of sizes. If I use a big float number as base parameter to cover the city and randomize the position, the chances of the NavMeshHit position being the corners of the map is huge.

    Look at this pic for a better example. I put 40 enemies to spawn and a huge part of them just spawned at the corners OR at the sides of the plane, while just two of them spawned next to the center.


    Is there a better way to do this? (Spawning enemies randomly based on NavMesh)