SystemBase overview
To create a managed system, implement the abstract class SystemBase
.
You must use the OnUpdate
system event callback to add the work that your system must perform every frame. All the other callback methods in the ComponentSystemBase
namespace are optional.
All system events run on the main thread. It's best practice to use the OnUpdate
method to schedule jobs to perform most of the work. To schedule a job from a system, you can use one of the following mechanisms:
Entities.ForEach
: Iterates over component data.Job.WithCode
: Execute a lambda expression as a single, background job.IJobEntity
: Iterates over component data in multiple systems.IJobChunk
: Iterates over data by archetype chunk.
The following example illustrates using Entities.ForEach
to implement a system that updates one component based on the value of another:
public struct Position : IComponentData
{
public float3 Value;
}
public struct Velocity : IComponentData
{
public float3 Value;
}
[RequireMatchingQueriesForUpdate]
public partial class ECSSystem : SystemBase
{
protected override void OnUpdate()
{
// Local variable captured in ForEach
float dT = SystemAPI.Time.DeltaTime;
Entities
.WithName("Update_Displacement")
.ForEach(
(ref Position position, in Velocity velocity) =>
{
position = new Position()
{
Value = position.Value + velocity.Value * dT
};
}
)
.ScheduleParallel();
}
}
Callback method order
There are several callback methods within SystemBase
that Unity invokes at various points during the system creation process, which you can use to schedule the work your system must do every frame:
OnCreate
: Called when a system is created.OnStartRunning
: Called before the first call toOnUpdate
and whenever a system resumes running.OnUpdate
: Called every frame as long as the system has work to do. For more information on what determines when a system has work to do, seeShouldRunSystem
.OnStopRunning
: Called beforeOnDestroy
. Also called whenever the system stops running, which happens if no entities match the system'sRequireForUpdate
, or if the system'sEnabled
property is set tofalse
. Note if noRequireForUpdate
is specified, the system will run continuously unless disabled or destroyed.OnDestroy
: Called when a system is destroyed.
The following diagram illustrates a system's event order:
A parent system group's OnUpdate
method triggers the OnUpdate
methods of all the systems in its group. For more information about how systems update, see Update order of systems.