Async Scheduler (Scripting/Threading)

2973292--228481--Async Objects Large.png
Asset Store Link

Want to make your games run smoother or execute code from thread on main? Then use Async Scheduler!

Documentation

Features
NEW Improved Task integration

  • Async.Instantiate returns ITask

  • Async.Run receives/returns ITask

  • Async.Run supports task with result

  • Async.Run
    Schedules code across multiple frames, preventing lag spikes. Capable of executing code from background thread on main

  • AsyncInsantiateGameObject
    Component that makes it easy to create spawn placeholders with editor-only previews

  • Async.Instantiate/Destroy
    Replaces Instantiate/Destroy.
    Useful for instantiating large quantities of objects at run time
    Thread Safe Instantiate/Destroy on a separate thread
    Prevent instantiation entirely by calling Destroy on pending objects

Example Usages:

  • Load saved level without loading screen
  • Pieces of a destructible meshes
  • Streaming in procedural content
  • Foliage around player as they explore
  • Procedural Asteroids/Planets/Stars
  • etc (Let me know how you use it!)

Want an easy way to manage threads?
Task for Unity
Want to spawn objects in Parallel?
Parallel for Unity

2 Likes

Looks very interesting!
Does it work for mobile? (Android/iOS/WP)

I would like to know how the objects are managed while in editor during level design process. Maybe I may use it for some buildings and trees that won’t be active in every part of my scene to reduce memory usage, but before buying it will be good watching at least a video of how it works in editor and gameplay mode…

By the way it seems that it works by code only, so I must create placeholders to load objects based on distance from player, calling the prefab via string (not reference, so it won’t be loaded in the scene until really nedded)… That would be great too!

Hey, glad you’re interested in Async Objects.

This should be compatible with mobile, I can test an Android build when I get home but I can’t think of any reason why it wouldn’t work. In fact the performance gain should be more apparent on mobile because of limited resources.

The intention of this asset is to replace Instantiate/Destroy calls in code with load balanced and thread safe Async.Instantiate/Destroy

If I understand you’re use case correctly, I have future plans for another asset that may be what you’re looking for. Which would be a discounted upgrade from Async Objects. It will be based on a system I’m using to optimize an entire galaxy so that stars/planets only spawn when the player is near a solar system (Uses Async Objects to spawn them).

Also eventually planning on releasing a Procedural Foliage spawning system that will randomly generate trees/bushes/etc around the player at run time as they explore. (But also consistently generate areas, so if you come back to the same area it will look the same). This will also be a discounted upgrade from Async Objects.

In the mean time I could write some useful components that help you use Async Objects in the way you want but it won’t be optimal (Having tons of objects checking the distance to the player is not cheap for the CPU).

Also I probably shouldn’t mention this for my sake, but I’m expecting all of my Assets to go on sale soon. I requested them to be part of a 30% sale but I’m not sure when that’s gonna happen. So you may want to wait until Async Objects goes on sale. You may also want to check out my other assets to optimize your game with threading, because Async Objects is thread-safe.
Parallel for Unity (Sale)
Task for Unity

That’s awesome! I plan buying it soon (even at full price, it looks amazing).

I’m trying to prototype a test where while in editor the object is visible to make it easier to level design, but once we click a button in inspector it will be removed from scene and will store its name in a string var to be instantiated in runtime (using a reference to prefab will cause it to be loaded into RAM on scene loading, which I don’t want). It will be like a prefab for prefab hehe. Using default instantiate for some items is OK, but not for many. Your tool will fit perfectly. I hope it will handle lots of different buildings if Unity really releases the memory for textures once they are unloaded /destroyed. About the common buildings repeated everywhere I don’t care, since their textures will be in memory for the entire session. My concern is using a lot of different objects.

Actually I already use more than 3k objects with distance checks with no problem, storing a reference to Camera.main so this is not called everytime. Of course I don’t make the check on every update, I use InvokeRepeating with a random time at start (let’s say from 2 to 10 secs for smaller objects and less for bigger ones like buildings). This way these checkings are distributed between frames. On most situations the player won’t notice objects appearing. There is still some cpu cost, but less than not having this at all. Also the distance checking is custom for each object, depending on the size and importance. Some close objects like trees are grouped, the checking is made on parent object just once.

I was using this to disable lights, projectors (I use them to fake night lights) and sometimes mesh renderers, with good results even on mobile.

I was using a trigger before, activating objects with OnTriggerEnter, but checking the tag Player on every object entering the big sphere was worse for me (at least in some Unity 4.x and first 5.x versions, I must try now). By the way even with trigger your tool will help, it is the loader.

I wish someday Unity will bring a native large map solution, until there… We must make crazy things, since they work and players are happy it is nice :smile:

So Instantiate as in GameObject instantiation? How’d that work?

Yea, you definitely don’t want every object checking distance every frame. It’s a good thing you distribute the work across frames… I would recommend having a centralized scheduler though and would be a good idea to perform the distance calculations in parallel background threads.

If you’d like I could look into creating a component that makes it easier to create a placeholder prefab in the scene that will call Async.Instantiate when you call a method on the component (From your distance checking code). Would that be useful for you?

That would be nice, if you have time… (I can create a simple one, but I don’t have any experience with editor scripts)

It would be awesome having a button while in inspector with the placeholder selected… To load/show the model/prefab inside the editor, but manually hide/remove it before saving the scene.

I was thinking about that, but I don’t know if creating the background thread to check distance will be more expensive than checking it on main thread, since it is just a small function. I didn’t have any problem with performance yet because of that calculations (measured in profiler).

I made a component “AsyncInstantiateGameObject” that has a bool showPreview. When true it shows a preview of the prefab in the scene which doesn’t save or show up in the hierarchy, and does not show up at runtime. I’ll try to update AsyncObjects soon with this component, but I’m not sure how long it will take for Unity to approve the Update.

I meant the thread would stay running in the background and do all the calculations and scheduling without blocking the main thread (Don’t create a thread for each object). Rather than occasionally running main thread distance calculations on objects in the scene. Just a suggestion though.

Nice, I bought your script today :smile:
May you please send this component to my e-mail? (I’ve posted a review so you know that I bought it)
marquinhosxp@gmail.com
Thanks in advance!

Looking into code, now comes another question… May this be used with Resources.Load… passing the prefab as string? (if I put the prefab in a reference on inspector, it will be loaded into memory as far as I know… That’s the thing that I’m trying to avoid. I’m not sure if Resources.Load… will be run in another thread, or will cause some spike.

I was testing here, with a simple script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AsyncObjects;

public class loadAsync : MonoBehaviour {

    public GameObject refObj;

    void Update () {
        if (Input.GetKeyUp (KeyCode.Return)) {
            //this causes spike because of Resources.load...
            Async.Instantiate(Resources.Load("onibus/pbcDesativado"), transform.position, Quaternion.identity, transform);
        } else if (Input.GetKeyUp (KeyCode.Space)) {
            //this does not causes it, it is very fast, but the refObj stays in memory
            //(that's the thing that I'm trying to avoid to save RAM on mobile)
            Async.Instantiate (refObj, transform.position, Quaternion.identity, transform);
        }
    }

}

My gameobject is a mid poly bus with lots of textures (without scripts, just for scenery).

Loading with Resources.Load seems to cause some spike, with reference a bit less. But in the second way the object stays in memory since scene startup…

I’ll wait your “AsyncInstantiateGameObject” to see how you have implemented it and test on Android later.

Thank you for purchasing/reviewing AsyncObjects!

I will be emailing the component shortly. I haven’t had the chance to fully test it so let me know if there’s any issues with it. I’ll be updating AsyncObjects this evening after work.

Yea I noticed Resources.Load is an expensive operation, the component supports reference or resource path and uses Resources.Load for 2nd option. I do have an idea of how to resolve that performance issue using Resources.LoadAsync but I’m heading to work now so I’ll look into it later.

Nice! Thank you very much for making that component, it will be really useful. With some improvements I think it will work well with Resources.LoadAsync. It would be nice having also an option to completely unload it (a public function on the component). I’ll try here with huge objects to see if the memory is proper released.
The preview feature in editor works the way I dreamed about it, thank you again :smile:

By the way one of my new assets got approved recently. You might want to check it out, it’s pretty cool :slight_smile:

1 Like

I don’t think I’ll get the chance to include Async.Load in 1.1

Version 1.1 will include new features:

  • Async.Run: Schedules code across multiple frames, preventing lag spikes. Capable of executing code from background thread on main (Not just Instantiate/Destroy)
  • AsyncInstantiateGameObject: Component that makes it easy to create spawn placeholders with editor-only previews

I will also be renaming it to Async Scheduler and may raise the price

1 Like

On sale for 30% off!

Version 1.1 released!

Forgot to mention this before but Async Scheduler now handles exceptions in your code more gracefully.

Version 1.2 released

  • Improved integration with Task for Unity

25% OFF SALE!

Excuse, Can I, or How can I, use Async.Destory on a GameObject which has been instantiated erlier? The examples of Asset and the document use it on Async and Async. But I don’t know how about GameObject. Visual Stdio says that Cannot convert from “UnityEngine.GameObject” to “Xefier.Threading.Asynchronous. Async<UnityEngine.GameObject>". In my project I need to instantiated a GameObject erlier to get its Transform as some others Gamejects’ Parent, or get an new Async's Transform. I am a new one to use Unity.

1 Like

If you are destroying a GameObject that was instantiated by Async.Instantiate() then you should be storing the Async that Async.Instantiate() returns (Like in the examples). The reason for this is because Async.Destroy is optimized so that if you destroy before the instantiate is triggered then both Instantiate/Destroy are prevented. Example:

private Async<GameObject> asyncGo;
private void OnEnable()
{
    asyncGo = Async.Instantiate(...);
}
private void OnDisable()
{
    Async.Destroy(asyncGo);
}

Also if you have Async and want to destroy the GameObject you can do this.

Async<Transform> asyncTransform = Async.Instantiate(...);
//...
Async.Destroy(asyncTransform, true);

If you want to destroy a GameObject that was NOT created with Async.Instantiate, then you can schedule it with Async.Run (Which is capable of scheduling ANY code)

//go is an existing GameObject
Async.Run(() => Object.Destroy(go));
2 Likes