A few simple light implementations of swarm behaviours in Unity - Part 1
- Abhishek Jathan
- 9 minutes ago
- 2 min read
It was a particularly not a productive day, so I decided I needed to do something just to satiate my need for accomplishment today.
Enter "Super Secret Project Which Requires A Small Swarm Of Flying Insects" or SSPWRASSOFI for short.
When swarms are considered, there are some things to think about first before implementation.
How many bugs are flying? ( the count of things )
How important is performance to you?
How much time do you have to muck about?
Is it 2D or 3D?
For me the answers to these questions were
Around 50 buggers flying around at max.
I would say 5/10.
A lot.
2D.
Now based on these considerations, you can now start the most straightforward implementation
Implementation 1: Simple C# Implementation
Smoothly moves the swarm controller (transform.position) toward the desiredPosition.
Calculates a shifting targetCenter using Perlin noise for gentle random motion (yeah its not just for VFX, it gives good continuous pseudo random values).
Smoothly interpolates the swarmCenter toward the targetCenter.This is what gives the swarm a gentle overall movement.
For each bee, generates a unique noise-based wanderOffset using noiseScale and beeWanderStrength.
Moves each bee toward its targetPos around the swarmCenter using beeMoveSpeed.
Adds a small sine-based flutter motion to each bee’s localPosition for visual liveliness.
Implementation 2: Slightly overcomplicated and quite honestly unnecessary
A really long time ago I figured out how to use Compute Shaders and the DrawMeshInstancedIndirect API to draw tonnes of grass. Now the reasoning for this is that if you create an individual gameobject for each blade of grass it ends up becoming too heavy because of all the overhead a gameobject has. What you can do with DrawMeshInstancedIndirect and its brothers and sisters is bypass the overhead of a gameobject to instantiate meshes.
Now this has its own pros and cons, but I won't go into that, another blog post maybe?
Now for this implementation, requires 3 things
A custom shader for the bug
A C# controller/dispatcher script
A compute shader
Custom simple unlit shader ( I'll convert it to a simple lit shader soon, chill )
C# controller/dispatcher script
Compute shader
How is this used?
Attach the dispatcher script to a gameobject. Link up the compute shader and a material which uses the custom shader. It also needs a mesh reference, for now I'm using the default Unity quad mesh which comes with the engine inbuilt.
It has some issues, but it works for now. I will probably not use Implementation 2 for SSPWRASSOFI, but it was a fun implementation to do just as a refresher to the workflow.
That's all for today folks. There will be another part coming which will be going into some details or the next part of the swarm implementation.
Cheers.
Happy learning!

