Unitythread by ngtrhieu - 2

Tween

Execute scripts on Unity main thread with ease

Unknown VersionOtherUpdated 51 days agoCreated on July 27th, 2020
Go to source

Unity Threading makes simple

Build Status Conventional Commits Package Version

Overview:

UnityThread is an utility script that allow you to register tasks to be run on the next Update/LateUpdate/FixedUpdate loop, from any thread.

Getting Started:

1. Install (via Unity Package Manager)

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
ShowPreviewPackage

Find Unity Thread package and click Install.
ShowPreviewPackage

2. Usage

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());

Tests

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.

Contributions

All discussions/pull requests are welcome.

Credits

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.

Show all projects by ngtrhieu