Skip to content

Latest commit

 

History

History
71 lines (48 loc) · 4.2 KB

File metadata and controls

71 lines (48 loc) · 4.2 KB

Reese's DOTS Randomization

Discord Shield

openupm

Exposes Unity.Mathematics.Random number generators compatible with Burst-compiled jobs.

Import

There are two ways to import this package, one being with OpenUPM, the preferred method, and the other via Git URL:

OpenUPM

This requires Node.js 12 or greater. cd to your project's directory and run:

npx openupm-cli add com.reese.random

Git

This requires Unity editor 2019.3 or greater. Copy one of the below Git URLs:

  • HTTPS: https://github.com/reeseschultz/ReeseUnityDemos.git#random
  • SSH: git@github.com:reeseschultz/ReeseUnityDemos.git#random

Then go to Window ⇒ Package Manager in the editor. Press the + symbol in the top-left corner, and then click on Add package from git URL. Paste the text you copied and finally click Add.

Usage

namespace YourNamespace {
    partial class YourJobSystem : SystemBase
    {
        protected override void OnUpdate()
        {
            var randomArray = World.GetExistingSystem<RandomSystem>().RandomArray;

            Entities
                .WithNativeDisableParallelForRestriction(randomArray)
                .ForEach((int nativeThreadIndex, ref YourComponent yourComponent) =>
                {
                    var random = randomArray[nativeThreadIndex];

                    yourComponent.SomeField = random.Next(0, 1000);

                    randomArray[nativeThreadIndex] = random; // This is NECESSARY.
                })
                .WithName("SomeJob")
                .ScheduleParallel();
        }
    }
}

We pass the array of random number generators to the Burst-compiled SomeJob, created through the Entities.ForEach syntactic sugar. Thread safety is accomplished by only modifying the state of each generator via the magic nativeThreadIndex (the current thread index of an executing job). Since we are managing safety ourselves, we must however pass the randomArray to WithNativeDisableParallelForRestriction. Yes, it's safe as long as you use the nativeThreadIndex as shown.

Note that, to ensure the state of a given generator updates upon each call to Execute, we must set it like so: RandomArray[nativeThreadIndex] = random. Otherwise, we'll only modify a copy of a given random generator object, and after a while things won't appear to be very random anymore!

Credits

Contributing

All contributions to this repository are licensed under MIT.