Search Unity

Question Prevent Navmesh Agent collision "jittering" if I spawn a lot

Discussion in 'Navigation' started by shazamo333, Apr 16, 2022.

  1. shazamo333

    shazamo333

    Joined:
    Jul 22, 2021
    Posts:
    4
    So I have a script which clones multiple copies of my navmeshagent ("player").

    However if I spawn too many at once they spawn at the same location so immediately collide and "jitter" from the spawn location.

    What's the best way to spawn them in a manner which prevents this kind of collision.



    My object instantiation code

    Code (CSharp):
    1.                 for (int i = 0; i < numberWeHaveToInstantiate; i++)
    2.                 {
    3.  
    4.                     clone = Instantiate(toClone, other.gameObject.transform.position, Quaternion.identity);
    5.                     clone.gameObject.name = $"Player(Clone {i + gameTracker.currentNumberOfPlayers + 1}";
    6.  
    7.                 }
     
  2. ChrisKurhan

    ChrisKurhan

    Joined:
    Dec 28, 2015
    Posts:
    268
    that's happening because you spawn them all on top of one another. You would need to find a spot on the NavMesh to spawn them that does not have another active NavMeshAgent on it. A crude approach may be to choose your spawn location, use the Physics.OverlapXXX API to see if there is a NavMeshAgent there, and move farther out and try again if there is an Agent occupying that space. I'm sure there's a more efficient way :)