How can I optimize my flocking script?

I have a flocking script for some ducks based on a youtube video I watched. The script works really well and I added my own basic obstacle avoidance system. However, performance is shocking! On average, every bird seems to take away 1 fps. That doesn’t sound too bad but it scales really poorly. I have a 4km x 4km map, and I want a lot of birds. With no birds, I have about 130-140fps. With 100 birds, that drops to 40-50fps. I would really like to be able to increase the number of birds to at least 200 and still have around 100fps. I know my code isn’t very well optimized but I just don’t how to do that. Below is are my two flocking scripts. I know for a fact that it is these scripts because the profiler has the flock.update() at about 20-30%. Each bird also has a ragdoll system so the player can shoot them and they will fall out of the sky. This means that each bird has a rigidbody and collider on each joint. I’ve also added an LOD system so the birds are culled outside a certain distance. Could someone please take a quick look at them and see if I’m doing something particularly expensive that could be done better?

GlobalFlock.cs

public class GlobalFlock : MonoBehaviour
{
    [SerializeField]
    private GameObject birdPrefab;
    [SerializeField]
    private Transform parent;

    [SerializeField]
    private int tankSize = 200;
    private float yOffset = 10;

    private static int numBirds = 100;
    public static GameObject[] allBirds = new GameObject[numBirds];

    void Start()
    {
        for (int i = 0; i < numBirds; i++)
        {
            //creating a random position within a 'tank' to spawn each bird
            Vector3 pos = new Vector3(Random.Range(-tankSize, tankSize), Random.Range(yOffset, yOffset + 1), Random.Range(-tankSize, tankSize));

            //makes the tanks position reletive to this transform
            pos += transform.position;

            //instantiating birds and parenting them to an empty to reduce clutter in the heirachy
            allBirds[i] = (GameObject)Instantiate(birdPrefab, pos, Quaternion.Euler(0, Random.Range(-360, 360), 0));
            allBirds[i].transform.parent = parent;
        }
    }
}

Flock.cs

public class Flock : MonoBehaviour
{
    private float speed;
    private float startSpeed;
    private float rotationSpeed = 4.0f;
    private Vector3 averageHeading;
    private Vector3 averagePosition;
    private float neighbourDistance = 4.0f;
    private bool flee;
    private Vector3 fleePos;
    private float fleeDistance = 100.0f;
    private float fleeRotationSpeed = 6.0f;
    private Transform[] rayTransforms;
    private int layer = 16;
    private int layerMask;
    private Vector3 goalPos;
    private Vector3 childPos;

    [SerializeField]
    private float rayLength;

    [HideInInspector]
    public bool ragdoll;

    private States states;

    void Start()
    {
        speed = Random.Range(4, 6);
        startSpeed = speed;
        states = FindObjectOfType<States>();

        rayTransforms = transform.GetChild(1).GetComponentsInChildren<Transform>();

        childPos = transform.GetChild(1).position;

        layerMask = ~(1 << layer);
    }

    void Update()
    {
        if (!ragdoll)
        {
            //randomly changing the goal position 5 times out of 10000
            if (Random.Range(0, 10000) < 3)
            {
                goalPos = new Vector3(Random.Range(-2000, 2000),
                                      Random.Range(0, 200),
                                      Random.Range(-2000, 2000));
            }

            //scare the birds - flee
            if (states.shoot)
            {
                fleePos = states.transform.GetChild(0).position;

                if (Vector3.Distance(fleePos, this.transform.position) < fleeDistance)
                {
                    flee = true;
                }
            }
            else
            {
                if (Vector3.Distance(fleePos, this.transform.position) >= fleeDistance)
                {
                    flee = false;
                }
            }

            if (Random.Range(0, 5) < 1)
                ApplyRules();

            transform.Translate(0, 0, Time.deltaTime * speed);
        }
    }

    void ApplyRules()
    {
        GameObject[] gos;
        gos = GlobalFlock.allBirds;

        Vector3 vCenter = Vector3.zero;
        Vector3 vAvoid = Vector3.zero;
        float gSpeed = 0.1f;

        float dist = 0;

        int groupSize = 0;

        foreach (GameObject go in gos)
        {
            if (go != this.gameObject && go)
            {
                dist = Vector3.Distance(go.transform.position, this.transform.position);
                if (dist <= neighbourDistance)
                {
                    vCenter += go.transform.position;
                    groupSize++;

                    if (dist < 1.0f)
                    {
                        vAvoid += this.transform.position - go.transform.position;
                    }

                    Flock anotherFlock = go.GetComponent<Flock>();
                    gSpeed += anotherFlock.speed;
                }
            }
        }

        Ray lRay = new Ray(childPos, rayTransforms[1].forward * rayLength);
        Ray rRay = new Ray(childPos, rayTransforms[2].forward * rayLength);
        Ray uRay = new Ray(childPos, rayTransforms[3].forward * rayLength);
        Ray dRay = new Ray(childPos, rayTransforms[4].forward * rayLength);

        if (Physics.Raycast(dRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(-1, 0, 0);
        }
        else if (Physics.Raycast(uRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(1, 0, 0);
        }
        else if (Physics.Raycast(lRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(0, 1, 0);
        }
        else if (Physics.Raycast(rRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(0, -1, 0);
        }


        if (flee)
        {
            Vector3 newFleePos = new Vector3(fleePos.x, transform.position.y, fleePos.z);
            Vector3 direction = transform.position - newFleePos;

            speed = Mathf.Lerp(speed, 9.0f, Time.deltaTime * 2);

            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * fleeRotationSpeed);
        }
        else
        {
            if (groupSize > 0)
            {
                vCenter = vCenter / groupSize + (goalPos - this.transform.position);
                speed = (speed == startSpeed) ? (gSpeed / groupSize) : Mathf.Lerp(speed, startSpeed, Time.deltaTime);

                Vector3 direction = (vCenter + vAvoid) - transform.position;

                if (direction != Vector3.zero)
                {
                    transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * rotationSpeed);
                }
            }
            else
            {
                speed = Mathf.Lerp(speed, startSpeed, Time.deltaTime);

                Vector3 direction = goalPos - this.transform.position;

                if (direction != Vector3.zero)
                {
                    transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * rotationSpeed);
                }
            }
        }
    }
}

I’m confused by this:

if (Random.Range(0, 5) < 1)
                ApplyRules();

If your intention is to run ApplyRules() every 5th frame, this is probably cheaper:

private int CurrentFrame;

private void Update()
    {
        CurrentFrame++;
        if (CurrentFrame >= 5)
        {
            ApplyRules()
            CurrentFrame = 0;
        }
    }

I actually made an entire thread dedicated to the cheapest way of making something run a few times a second. I tested it multiple times, you can read about it here: Best method to check something often, without dragging performance - Unity Engine - Unity Discussions

Also, Random.Range is truly random, which means that it will sometimes run ApplyRules() many times in a row, and then not run for a while because it’s all random.

I can imagine that using Random.Range in the Update function is quite taxing. Then, ApplyRules() is a pretty long function, and it is extremely expensive (explained below). That’s where I think most of the performance drag is from.

You’re creating Vector3s, floats and ints dynamically, which is slower than if you had already created them once at start. I’m talking about this:

float gSpeed = 0.1f;
GameObject[] gos;
gos = GlobalFlock.allBirds;
float dist = 0;
int groupSize = 0;

Normally it’s not a big deal, but we’re doing it many times a second, little stuff like that can matter, especially if you’re running 200 instances of the same script 20 times a second or so.

Then, you’re doing foreach. Since your array is large (you said 200 birds), that foreach is probably the most expensive part of the script. Even worse, you’re using GetComponent() INSIDE the foreach that is running every few frames. I’m talking about this:

Flock anotherFlock = go.GetComponent<Flock>();

Other than that it seems OK.

I was suspecting that, that and go.GetComponent(). What is my alternative though? Maybe I could find the GameObject[ ] gos in the start function and then iterate through the indexes of GameObject[ ] gos with a for loop. Then I could make an array of Flock and find that with go.GetComponent() in the start function.

I’ll make those changes and see how it goes, then I’ll post here again to see if it could be further improved.

I think you should create another array of those components. That way you use GetComponent just once in the Start (since no one cares if the game starts 0.2 seconds or so later). The Update function is very expensive and it’s important move as much stuff from there to Start (or another function that’s called once) as possible.

1 Like

to avoid the GetComponent call, simply make Allbirds a List, not GameObject[ ]. and have the Flock script add and remove itself from that array in OnEnable/OnDisable. furthermore the more code you can shift into global flock the less overhead Unity has to do with 200 bird update calls

2 Likes

Thanks everyone! The performance has improved drastically. I now have 250 ducks with 60-70fps! I’ve posted my code below to see if there’s anything else that I can do to improve the performance.

GlobalFlock.cs

//bird
    [SerializeField]
    private GameObject birdPrefab;


    //tank
    [SerializeField]
    private int tankSize = 200;

   
    //spawning
    private static float yOffset = 5;
    private static int numBirds = 200;

    //public static GameObject[] allBirds = new GameObject[numBirds];
    [HideInInspector]
    public List<GameObject> allBirdsGameObject = new List<GameObject>();
    [HideInInspector]
    public List<Flock> allBirdsFlock = new List<Flock>();

    [SerializeField]
    private Transform parent;

    void Start()
    {
        for (int i = 0; i < numBirds; i++)
        {
            //creating a random position within a 'tank' to spawn each bird
            Vector3 pos = new Vector3(Random.Range(-tankSize, tankSize), Random.Range(yOffset, yOffset + 10), Random.Range(-tankSize, tankSize));

            //making the random position relitive to the player
            pos += transform.position;

            //instantiating birds and parenting them to an empty to reduce clutter in the heirachy
            allBirdsGameObject.Add((GameObject)Instantiate(birdPrefab, pos, Quaternion.Euler(0, Random.Range(-360, 360), 0)));
            allBirdsGameObject[i].transform.parent = parent;

            //adding the flock component
            allBirdsFlock.Add(allBirdsGameObject[i].GetComponent<Flock>());
        }
    }

Flock.cs

//speeds
    private float speed;
    private float startSpeed;
    private float rotationSpeed = 2.0f;
    private float groupSpeed = 0.1f;

    //group
    private Vector3 averageHeading;
    private Vector3 averagePosition;
    private float neighbourDistance = 4.0f;
    private Vector3 vCenter = Vector3.zero;
    private Vector3 vAvoid = Vector3.zero;
    private Vector3 groupGoalPos = Vector3.zero;
    private List<GameObject> birds;
    private List<Flock> otherBirds;
    private float dist = 0;
    private int groupSize = 0;

    //flee
    private bool flee;
    private Vector3 fleePos;
    private float fleeDistance = 200.0f;
    private float fleeRotationSpeed = 8.0f;

    //obstacle avoidence
    private int layer = 16;
    private int layerMask;
    private Vector3 newFleePos;
    private Vector3 direction;
    //rays
    [SerializeField]
    private float rayLength;
    private Transform[] rayTransforms;
    private Vector3 rayStartPos;
    private Ray lRay;
    private Ray rRay;
    private Ray uRay;
    private Ray dRay;

    //movement
    private Vector3 goalPos;
    private Vector3 resultingGroupDirection;
    private Vector3 resultingAloneDirection;

    //ragdoll
    [HideInInspector]
    public bool ragdoll;

    //other
    private int currentFrame;

    //components
    private States states;
    private GlobalFlock globalFlock;

    void Start()
    {
        //finding other components
        states = FindObjectOfType<States>();
        globalFlock = FindObjectOfType<GlobalFlock>();

        //setting the speed of each bird
        speed = Random.Range(3, 6);
        startSpeed = speed;
       

        //group
        birds = globalFlock.allBirdsGameObject;
        otherBirds = globalFlock.allBirdsFlock;


        //obstacle avoidence
        //finding the transforms of all the ray offsets
        rayTransforms = transform.GetChild(1).GetComponentsInChildren<Transform>();
        //finding the starting position for the rays
        rayStartPos = transform.GetChild(1).position;
       
        //setting the layer mask so the duck doesn't trigger the ray itself
        layerMask = ~(1 << layer);


        //randomly offsetting the current frame so ducks will apply rules at different times
        currentFrame = Random.Range(0, 10);
    }

    void Update()
    {
        if (!ragdoll)
        {
            //randomly changing the goal position 5 times out of 10000
            if (Random.Range(0, 10000) < 3)
            {
                goalPos = new Vector3(Random.Range(-2000, 2000), Random.Range(20, 200), Random.Range(-2000, 2000));
            }

            //scare the birds - flee
            if (states.shoot)
            {
                //find the position of the player
                fleePos = states.transform.GetChild(0).position;

                //check if the bird is in range of the player
                if (Vector3.Distance(fleePos, this.transform.position) < fleeDistance)
                {
                    flee = true;
                }
            }
            else
            {
                //check to see if the bird is out of range of the player
                if (Vector3.Distance(fleePos, this.transform.position) >= fleeDistance && flee == true)
                {
                    flee = false;
                }
            }

            //appying rules every 7 frames
            currentFrame++;
            if (currentFrame >= 7)
            {
                //appying the rules and resetting the frame counter to zero
                ApplyRules();
                currentFrame = 0;
            }

            //moving the bird forward
            transform.Translate(0, 0, Time.deltaTime * speed);
        }
    }

    void ApplyRules()
    {
        //resetting some variables
        dist = 0;
        groupSize = 0;

        //looping through all of the birds
        for (int i = 0; i < birds.Count; i++)
        {
            //checking if the bird is not this one, and if it exists (birds that have been shot and claimed by the player will be destroyed)
            if (birds[i] != this.gameObject && birds[i])
            {
                //calculating the distance between the bird and this bird
                dist = Vector3.Distance(birds[i].transform.position, this.transform.position);
                //check if the distance is less than the neighbourDistance threshold
                if (dist <= neighbourDistance)
                {
                    //finding the center of the group
                    vCenter += birds[i].transform.position;

                    //check if the bird is too close to this bird
                    if (dist < 1.0f)
                    {
                        //moving the avoid velocity away from the bird so they don't collide
                        vAvoid += this.transform.position - birds[i].transform.position;
                    }

                    //finding the average speed of the group
                    groupSpeed += otherBirds[i].speed;

                    //finding the average goal pos of the group
                    groupGoalPos += otherBirds[i].goalPos;

                    //incrementing the size of the group
                    groupSize++;
                }
            }
        }

        //creating all of the rays
        lRay = new Ray(rayStartPos, rayTransforms[1].forward * rayLength);
        rRay = new Ray(rayStartPos, rayTransforms[2].forward * rayLength);
        uRay = new Ray(rayStartPos, rayTransforms[3].forward * rayLength);
        dRay = new Ray(rayStartPos, rayTransforms[4].forward * rayLength);

        //checking if each ray is colliding with something
        if (Physics.Raycast(dRay, rayLength, layerMask))
        {
            //offsetting the birds rotation away from the obstacle
            transform.localEulerAngles += new Vector3(-1, 0, 0);
        }
        else if (Physics.Raycast(uRay, rayLength, layerMask))
        {
            //offsetting the birds rotation away from the obstacle
            transform.localEulerAngles += new Vector3(1, 0, 0);
        }
        else if (Physics.Raycast(lRay, rayLength, layerMask))
        {
            //offsetting the birds rotation away from the obstacle
            transform.localEulerAngles += new Vector3(0, 1, 0);
        }
        else if (Physics.Raycast(rRay, rayLength, layerMask))
        {
            //offsetting the birds rotation away from the obstacle
            transform.localEulerAngles += new Vector3(0, -1, 0);
        }

        //changing the rotation to flee from the player (only if flee is true)
        if (flee)
        {
            //creating a position, x and z are at the players position, but y remains the same (height of the bird)
            newFleePos = new Vector3(fleePos.x, transform.position.y, fleePos.z);
            //setting the direction for the bird to flee
            direction = transform.position - newFleePos;

            //increases the speed
            speed = Mathf.Lerp(speed, 8.0f, Time.deltaTime * 2);

            //applies the rotation
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * fleeRotationSpeed);
        }
        else
        {
            //apply the basic boid rules if the bird is part of a group
            if (groupSize > 0)
            {
                //averaging the group goal position by dividing it by the group size
                groupGoalPos /= groupSize;

                //averaging the center of the group and offsetting it by the direction of the average group goal position
                vCenter = (vCenter / groupSize) + (groupGoalPos - this.transform.position);

                //change the speed to match the average group speed
                speed = groupSpeed / groupSize;

                //create the resulting direction based off the center and goal position of the group, the force needed to avoid any birds that are too close, and the current birds position
                resultingGroupDirection = (vCenter + vAvoid) - transform.position;

                //appying the resulting direction
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(resultingGroupDirection), Time.deltaTime * rotationSpeed);
            }
            else //apply rules for if the bird is alone
            {
                //moving the speed to match the original speed of the bird
                speed = Mathf.Lerp(speed, startSpeed, Time.deltaTime);

                //creating the resulting direction to head towards (head towards the goal position)
                resultingAloneDirection = goalPos - this.transform.position;

                //appying the resulting direction
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(resultingAloneDirection), Time.deltaTime * rotationSpeed);
            }
        }
    }

i could not test this but hope it works , you would have to fiddle with the concept and values ,sorry if it doesnt deliver right off the bat…

    int iterator_index=0;
    public int global_update_frame=1;
    public int group_update_frame=5;
    public int adjust_update_frame=4;
    public int behaviour_update_frame=3;
    public bool update_all=false;

    void Update()
    {
        if (!ragdoll)
        {
            currentFrame++;
            if (currentFrame >= global_update_frame)
            {
                //randomly changing the goal position 5 times out of 10000
                if (Random.Range(0, 10000) < 3)
                {
                    goalPos = new Vector3(Random.Range(-2000, 2000), Random.Range(20, 200), Random.Range(-2000, 2000));
                }
            
                //scare the birds - flee
                if (states.shoot)
                {
                    //find the position of the player
                    fleePos = states.transform.GetChild(0).position;
                
                    //check if the bird is in range of the player
                    if (Vector3.Distance(fleePos, this.transform.position) < fleeDistance)
                    {
                        flee = true;
                    }
                }
                else
                {
                    //check to see if the bird is out of range of the player
                    if (Vector3.Distance(fleePos, this.transform.position) >= fleeDistance && flee == true)
                    {
                        flee = false;
                    }
                }
        
                //appying the rules and resetting the frame counter to zero
                ApplyRules();
                currentFrame = 0;
            }
        
            //moving the bird forward
            transform.Translate(0, 0, Time.deltaTime * speed);
        }
    }

    void update_group(int frame=5, bool one_at_a_time=true)
    {
        if(Time.frameCount %frame ==0)
        {
            if(!one_at_a_time)
            {
                //looping through all of the birds
                for (int i = 0; i < birds.Count; i++)
                {
                    //checking if the bird is not this one, and if it exists (birds that have been shot and claimed by the player will be destroyed)
                    if (birds[i] != this.gameObject && birds[i])
                    {
                        //calculating the distance between the bird and this bird
                        dist = Vector3.Distance(birds[i].transform.position, this.transform.position);
                        //check if the distance is less than the neighbourDistance threshold
                        if (dist <= neighbourDistance)
                        {
                            //finding the center of the group
                            vCenter += birds[i].transform.position;
                        
                            //check if the bird is too close to this bird
                            if (dist < 1.0f)
                            {
                                //moving the avoid velocity away from the bird so they don't collide
                                vAvoid += this.transform.position - birds[i].transform.position;
                            }
                        
                            //finding the average speed of the group
                            groupSpeed += otherBirds[i].speed;
                        
                            //finding the average goal pos of the group
                            groupGoalPos += otherBirds[i].goalPos;
                        
                            //incrementing the size of the group
                            groupSize++;
                        }
                        else continue;
                    }
                    else continue;
                }
            }

            else
            {
                //checking if the bird is not this one, and if it exists (birds that have been shot and claimed by the player will be destroyed)
                if (birds[iterator_index] != this.gameObject && birds[iterator_index])
                {
                    //calculating the distance between the bird and this bird
                    dist = Vector3.Distance(birds[iterator_index].transform.position, this.transform.position);
                    //check if the distance is less than the neighbourDistance threshold
                    if (dist <= neighbourDistance)
                    {
                        //finding the center of the group
                        vCenter += birds[iterator_index].transform.position;
                    
                        //check if the bird is too close to this bird
                        if (dist < 1.0f)
                        {
                            //moving the avoid velocity away from the bird so they don't collide
                            vAvoid += this.transform.position - birds[iterator_index].transform.position;
                        }
                    
                        //finding the average speed of the group
                        groupSpeed += otherBirds[iterator_index].speed;
                    
                        //finding the average goal pos of the group
                        groupGoalPos += otherBirds[iterator_index].goalPos;
                    
                        //incrementing the size of the group
                        groupSize++;
                    }
                }

                if(iterator_index!=birds.Count-1)
                    iterator_index++;
                else iterator_index=0;

            }

        }

    }

    void adjust_for_steer(int frame=4)
    {
        if(Time.frameCount %frame==0)
        {
            //creating all of the rays
            lRay = new Ray(rayStartPos, rayTransforms[1].forward * rayLength);
            rRay = new Ray(rayStartPos, rayTransforms[2].forward * rayLength);
            uRay = new Ray(rayStartPos, rayTransforms[3].forward * rayLength);
            dRay = new Ray(rayStartPos, rayTransforms[4].forward * rayLength);
        
            //checking if each ray is colliding with something
            if (Physics.Raycast(dRay, rayLength, layerMask))
            {
                //offsetting the birds rotation away from the obstacle
                transform.localEulerAngles += new Vector3(-1, 0, 0);
            }
            else if (Physics.Raycast(uRay, rayLength, layerMask))
            {
                //offsetting the birds rotation away from the obstacle
                transform.localEulerAngles += new Vector3(1, 0, 0);
            }
            else if (Physics.Raycast(lRay, rayLength, layerMask))
            {
                //offsetting the birds rotation away from the obstacle
                transform.localEulerAngles += new Vector3(0, 1, 0);
            }
            else if (Physics.Raycast(rRay, rayLength, layerMask))
            {
                //offsetting the birds rotation away from the obstacle
                transform.localEulerAngles += new Vector3(0, -1, 0);
            }
        }
    }

    void flee_behaviour_update(int frame=3)
    {
        if(Time.frameCount %frame==0)
        {
            //changing the rotation to flee from the player (only if flee is true)
            if (flee)
            {
                //creating a position, x and z are at the players position, but y remains the same (height of the bird)
                newFleePos = new Vector3(fleePos.x, transform.position.y, fleePos.z);
                //setting the direction for the bird to flee
                direction = transform.position - newFleePos;
            
                //increases the speed
                speed = Mathf.Lerp(speed, 8.0f, Time.deltaTime * 2);
            
                //applies the rotation
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * fleeRotationSpeed);
            }
            else
            {
                //apply the basic boid rules if the bird is part of a group
                if (groupSize > 0)
                {
                    //averaging the group goal position by dividing it by the group size
                    groupGoalPos /= groupSize;
                
                    //averaging the center of the group and offsetting it by the direction of the average group goal position
                    vCenter = (vCenter / groupSize) + (groupGoalPos - this.transform.position);
                
                    //change the speed to match the average group speed
                    speed = groupSpeed / groupSize;
                
                    //create the resulting direction based off the center and goal position of the group, the force needed to avoid any birds that are too close, and the current birds position
                    resultingGroupDirection = (vCenter + vAvoid) - transform.position;
                
                    //appying the resulting direction
                    transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(resultingGroupDirection), Time.deltaTime * rotationSpeed);
                }
                else //apply rules for if the bird is alone
                {
                    //moving the speed to match the original speed of the bird
                    speed = Mathf.Lerp(speed, startSpeed, Time.deltaTime);
                
                    //creating the resulting direction to head towards (head towards the goal position)
                    resultingAloneDirection = goalPos - this.transform.position;
                
                    //appying the resulting direction
                    transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(resultingAloneDirection), Time.deltaTime * rotationSpeed);
                }
            }
        }
    }

    void ApplyRules()
    {
        //resetting some variables
        dist = 0;
        groupSize = 0;

        update_group(group_update_frame,update_all);
        adjust_for_steer(adjust_update_frame);
        flee_behaviour_update(behaviour_update_frame);
    }

p.s ,it may happen that you need to swap,the global frame update for a per frame update

Getting past 60 FPS is normally a case of turning off VSync. :P. Look at the profiler and measure in milliseconds instead.

On to specifics

  • You can lower the calculation frequency dramatically without doing much damage to quality.
  • Why are you looping through 200 birds every update? You can sift this down dramatically by leveraging physics system or implementing your own quadtree
  • Work in distance squared space instead of distance space
  • Consider updating all voids from a central script rather then letting Unity do it for you

But all said it looks pretty decent. There is nothing obvious.

1 Like

You may want to consider swapping a bird out for a ragdoll version when its hit. That way you can remove a few of the expensive components and shift them onto the dead bird prefab.

Also I forgot to mention that you can pretty much disable the script when you kill the bird. That way as you kill more birds you can add more without having the dead ones needlessly taking resources.

Yes, I discovered that a while ago actually. It was a very nice discovery, went from 60fps to like 300. This was before all the birds and trees from my terrain though.

I did this but past about one in every 10 frames it didn’t make a difference, I’ll just leave it on 10 for now.

Maybe I could sort through every odd bird on one frame and every even bird on the other? Would that make a difference? I don’t know, I’ll try it. Also, what do you mean by leveraging physics system and implementing my own quadtree?

I just gave that a shot, but interestingly it seemed to chop of 10fps or so when I used square distance so I think I’ll just stick with distance.

This is a good idea actually. I did remove all the rigidbodies and colliders on all of the joints of the birds and added one capsule collider and a box collider on the edge of the wings to stop it rolling through the ground. That seemed to have a huge impact on performance. But swapping the birds out for another one is a great idea, however I’m not too sure it would work well if the bird was up close, I think the player would notice it quite clearly.

Already doing that. My ragdoll script disables the animator, the Flock.cs, and turns off isKinematic on the rigidbody. Then once the player claims the bird, it is destroyed.