Performance Questions

Not sure if the Unity Answers or Forum is the better choice.

  • I have a lot of AI in my game(100+ active AI, 2000+ not active AI objects). They check distances between them to see if they are close enough.

Now my Question is what is faster(both run only once per second):

  1. Just get all those objects tagged as “Pirate”, “Police” etc. into GameObject arrays and then do this:

    PoliceObjects = GameObject.FindGameObjectsWithTag(“Police”);
    PirateObjects = GameObject.FindGameObjectsWithTag(“Pirate”);

    foreach (GameObject police in PoliceObjects )
    {
    //Check for distance and then act
    }
    foreach( Same Goes for other 5 arrays of tagged objects)

  2. Every active object is saved to HashSet Collection. But I think FindGameObjectsWithTag already loops only through active objects.

    //Note objectHashSetDatabase can have up to 200+ active objects AI
    foreach (GameObject object in objectHashSetDatabase )
    {
    if(object.tag == “Police”)
    //Check for distance and then act
    if(object.tag == “Something else”)
    }

  3. Does better method exists? :smiley:

You need to look into spatial partitioning systems to ease the workload. A short summary of the idea:

Split your scene into a number of cells (cubes if 3D, squares if 2D) and store those in a multidimensional array. An AI is always a member of a cell, corresponding to the area of the scene the AI currently occupies. When an AI moves, update its cell membership.

Now, in the above, you no longer have to test distance against every single gameobject. It is enough to test against a cell since, if the distance to a cell exceeds whatever threshold you define, you can assume the same counts for all members of the cell. This allows you to skip calculations for each of the members, which becomes expensive with great numbers, as you’ve noticed.

If the distance to a cell does not exceed your defined threshold, you need to treat the cell’s members individually.

The science now is to choose cell size wisely such that a reasonable tradeoff between cell iteration and member iteration becomes faster than simply iterating over all AIs.

Many algorithms in computer graphics use various versions of spatial partitioning including, but not limited to, ray casting, collision detection and occlusion culling.