1. Download
Download & import the unity package.
2. ThreadHarmonizer Manager
Add the ThreadHarmonizer Manager to the scene, by right clicking on the scene hierarchy. The manager must be present in the scene for all multithreaded files to execute during the update call. Additionally, you can adjust the settings for the internal code by clicking on it.
Thread Ratio
Select the ratio of threads to CPU cores to be utilized. Since Unity already employs separate threads, it is recommended to allocate 25% to 50% of available cores.
Optimization Interval
The interval sequence determines the timing of performance-enhancing changes, measured in seconds.
3. Adjust your Scripts
Now all that’s left is to update your scripts to support multithreading. Simply select all your files at once, then right-click to choose ‘Turn to Multithreaded Script.’ This process will handle most changes, potentially all of them. By using this function, your scripts will no longer inherit from MonoBehaviour but from MonoBehaviourMultithreaded. This transition doesn’t impose any limits; instead, it introduces a few new functions, which are also documented.
However, there are two things you will have to do manually. If you use public variables, which are accessed from multiple parallel functions, ensure they are thread-safe to prevent potential issues. For example, a public int counter should be accessed using the System.Threading.Interlocked
class.
Since Unity’s API isn’t thread-safe, meaning it’s not designed to be accessed from multiple threads simultaneously, it’s crucial to access variables like GameObjects and functions related to the Unity engine from the main thread only. Accessing them from other threads can lead to unexpected behavior or crashes. Therefore, it’s important to ensure that any interactions with Unity’s API are done from the main thread. Getting and setting the position of a GameObject should be done inside the normal Update function, while everything else you would normally do with it should be handled inside the ParallelUpdate function.
Should you wish to revert a script to its normal state, you can easily do so by selecting the ‘Revert to Normal Script’ option below. Additionally, if you intend to create a new script for multithreading, you can find this option under ‘Create -> C# Script (Multithreaded).’
To clarify, it’s entirely possible and recommended for a script to use the normal update function and run more complex code in multithreaded form within the same script. The normal update function remains single-threaded, while the ThreadHarmonizer update runs all provided functions parallel as fast as possible.”