UnityThread is an utility script that allow you to register tasks to be run on the next Update/LateUpdate/FixedUpdate loop, from any thread.
Open your Packages/manifest.json
file and add the npm
as the registry, with the scope "com.ngtrhieu" as followed:
{
"dependencies": {
<...your existing dependencies>
},
"scopedRegistries": [
<...other registries, if any>,
{
"name": "npm",
"url": "https://registry.npmjs.org/",
"scopes": ["com.ngtrhieu"]
}
]
}
Open Unity, go to Package Manager (Windows/Package Manager)
Inside Package Manager, select Advanced/Show Preview Packages
Find Unity Thread package and click Install.
You will need to call CreateUnityThreadInstance()
before accessing any UnityThread API.
using UnityEngine;
UnityThread.CreateUnityThreadInstance();
Schedule your code to be executed on the next Update/FixedUpdate/LateUpdate loop simply by doing:
using UnityEngine;
UnityThread.ExecuteInUpdate(() => {
// this code will be executed on the next Update.
});
UnityThread.ExecuteInLateUpdate(() => {
// this code will be executed on the next LateUpdate.
});
UnityThread.ExecuteInFixedUpdate(() => {
// this code will be executed on the next FixedUpdate.
});
// This coroutine will be executed on the next Update loop.
UnityThread.ExecuteCoroutine(ACoroutine());
Open Packages/manifest.json
and add the following item:
{
"dependencies": {
<...your existing dependencies>
},
"testables": [
<...your existing packages, if any>
"com.ngtrhieu.unitythread"
]
}
Open Unity Test Runner (Window/General/Test Runner). UnityThread tests should be shown under PlayMode tests.
All discussions/pull requests are welcome.
This code has been circulated and adopted among my team so I couldn't remember where we originally took this from. The earliest resemblance I can find is in this StackOverflow, so I would like to give credits to this answer.