I’m about to begin work on a project that involves several spaceships on a 2D plane going at it with missiles in combat. There will be at least four ships on each side, and each ship will be firing multiple missiles. The scripts attached to each ship and missile will be the same c# script and I could potentially see several hundred entities at once in larger games. Is there a way that I could have each instance’s calculations run under its own thread as to allow easy multicore scaling? If so, how hard would it be to do?
As you may already be aware, Unity does not use multithreading (for the most part).
Could you have multiple threads?
Yes you can. You would have to use System.Threading. But keep in mind that most of Unity’s functions are not thread safe.
How hard would it be to do?
The difficulty depends on how well you know how to use threads. Keeping track of things that are occurring at the same time can become difficult. There also doesn’t seem to be much support for multithreading in Unity so that’s also something to keep in mind.
Not many CPU’s out there can run 100 threads at once. If I remember correctly an intel i5 cpu would have at most 8 threads running (4 threads for laptops), therefore your method of squeezing out extra performance would still be a bit problematic. Most games when they use multithreading, they thread the logic and physics on different threads. As kacyesp said, most Unity functions are not thread safe, so that’s another problem.
As for hundreds of entities, as long as you are coding it efficiently, shouldn’t be much of a problem. However, if you are finding you have performance issues, you probably need to roll your own lightweight 2D physics (just colliders should be enough for your purpose), and do plenty of performance tweaks to make your it runs with decent FPS.