docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Use the job system with Entities

    The Entities package and Unity's DOTS architecture uses the C# Job System extensively. Whenever possible, you should use jobs in your system code.

    The SystemBase class provides Entities.ForEach and Job.WithCode to implement your application's logic as multithreaded code. In more complex situations, you can use IJobChunk's Schedule() and ScheduleParallel() methods, to transform data outside the main thread. Entities.ForEach is the simplest to use and typically requires fewer lines of code to implement.

    ECS schedules jobs on the main thread in the order that your systems are in. When you schedule jobs, ECS keeps track of which jobs read and write which components. A job that reads a component is dependent on any prior scheduled job that writes to the same component and vice versa. The job scheduler uses job dependencies to determine which jobs it can run in parallel and which must run in sequence.

    For example, the following system updates positions:

        using Unity.Burst;
        using Unity.Collections;
        using Unity.Entities;
        using Unity.Jobs;
        using Unity.Transforms;
        
        public class MovementSpeedSystem : SystemBase
        {
            // OnUpdate runs on the main thread.
            protected override void OnUpdate()
            {
                Entities
                    .ForEach((ref Translation position, in MovementSpeed speed) =>
                        {
                            float3 displacement = speed.Value * dt;
                            position = new Translation(){
                                    Value = position.Value + displacement
                                };
                        })
                    .ScheduleParallel();
            }
        }
    

    For more information about systems, see System concepts.

    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)