Search Unity

Question Solution for large amounts of ai agents?

Discussion in 'Navigation' started by jessee03, Sep 30, 2022.

  1. jessee03

    jessee03

    Joined:
    Apr 27, 2011
    Posts:
    729
    Has anyone found a good solution when using a large amount of navmesh agents? I found a threading script recently that has improved performance by a decent amount but still if I hit around 50 agents I get a large delay for calculating agent movement. Is there a way to improve this code to handle large amounts of agents using SetDestination()?


    Code (CSharp):
    1. using System.Threading;
    2. using UnityEngine;
    3.  
    4. public class ThreadedBehaviour : MonoBehaviour
    5. {
    6.     Thread ChildThread = null;
    7.     EventWaitHandle ChildThreadWait = new EventWaitHandle(true, EventResetMode.ManualReset);
    8.     EventWaitHandle MainThreadWait = new EventWaitHandle(true, EventResetMode.ManualReset);
    9.  
    10.     void ChildThreadLoop()
    11.     {
    12.         ChildThreadWait.Reset();
    13.         ChildThreadWait.WaitOne();
    14.  
    15.         while (true)
    16.         {
    17.             ChildThreadWait.Reset();
    18.  
    19.             // Do Update
    20.  
    21.             WaitHandle.SignalAndWait(MainThreadWait, ChildThreadWait);
    22.         }
    23.     }
    24.  
    25.     void Awake()
    26.     {
    27.         ChildThread = new Thread(ChildThreadLoop);
    28.         ChildThread.Start();
    29.     }
    30.  
    31.     void Update()
    32.     {
    33.         MainThreadWait.WaitOne();
    34.         MainThreadWait.Reset();
    35.         ChildThreadWait.Set();
    36.     }
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    There are a few more improvements you can take:
    - Precalculate on Start the available Paths. That way you dont have to calculate them runtime,
    that for example helps alot if you have AI for example with predefined paths. If the Path is not available
    ofc. you have to calculate then, best idea would be, outside of the main thread, yes.
    - use LODs if you have AI + Animations, remove the Animations at a certain range, disable the Mesh from the AI at a very large range or use a very low poly mesh
    - If you have Animations, also use Animation LODs with less bones at a large range, that improves the performance as well.
    - NEVER set Destination in Update loop, if you have "Loads" of AI, you will need a good architecture setup. That will improve your performance also by alot.

    Overall, ECS is starting to reach 1.0 which means step by step it will be production ready, with the ECS you can reach a much bigger number of running AI. Althought its not Required to develop a large scale Game. We have over 1200 AI running with a huge high quality asset world. We run about 60-110 frames depending on the location.