Adding thread safety to the generic singleton
In this section, we’re going to focus on making our generic singleton thread-safe by guarding against different threads potentially creating more than one instance of the singleton. For example, imagine you need to process an algorithm that finds all enemies within a set distance, as well as their positions and orientations. Doing this on the main thread might decrease your frame rate and slow down other processes in your game. However, if you separate the algorithm into a separate thread, Unity’s main thread is free to keep running the essential parts of the game while the sub-thread does its work.
Thread safety in multithreaded environments is a huge topic and has additional implications when using Unity APIs. For a deeper dive, check out .NET Multithreading by Alan Dennis at https://www.manning.com/books/net-multithreading.
If you’re new to the concept of threading, it helps to think of your...