Create the system for the spawner example
This task shows you how to create a Burst-compatible system that queries for a component, reads and writes component values, and instantiates entities at runtime.
ECS workflow overview
This task is the fourth task in a series of five tasks that show you how to create and optimize behavior in an ECS system. At the end of the tasks, you will have a spawner system that reads and writes component data, and instantiates entities. This workflow contains the following tasks:
- Create the subscene for the spawner example
- Create a component for the spawner example
- Create the spawner entity for the spawner example
- Create the system for the spawner example
- Optimize the system for the spawner example
Each task is a prerequisite for the subsequent tasks.
Create the spawner system
- Create a new C# script called
SpawnerSystem
and replace the contents of the file with the below code example. When you enter Play mode, Unity creates a world instance and adds every system to this default world. For more information, see Initialization. - Enter Play mode. You should see that the system instantiates the Prefab you assigned at the rate that you set. If you open the Entities Hierarchy window, you can see the entities appear as the system instantiates them. Note: If you can't see the entities in the Scene view, make sure to install and setup Entities Graphics and either the Universal Render Pipeline or the High Definition Render Pipeline.
using Unity.Entities;
using Unity.Transforms;
using Unity.Burst;
[BurstCompile]
public partial struct SpawnerSystem : ISystem
{
public void OnCreate(ref SystemState state) { }
public void OnDestroy(ref SystemState state) { }
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
// Queries for all Spawner components. Uses RefRW because this system wants
// to read from and write to the component. If the system only needed read-only
// access, it would use RefRO instead.
foreach (RefRW<Spawner> spawner in SystemAPI.Query<RefRW<Spawner>>())
{
ProcessSpawner(ref state, spawner);
}
}
private void ProcessSpawner(ref SystemState state, RefRW<Spawner> spawner)
{
// If the next spawn time has passed.
if (spawner.ValueRO.NextSpawnTime < SystemAPI.Time.ElapsedTime)
{
// Spawns a new entity and positions it at the spawner.
Entity newEntity = state.EntityManager.Instantiate(spawner.ValueRO.Prefab);
// LocalPosition.FromPosition returns a Transform initialized with the given position.
state.EntityManager.SetComponentData(newEntity, LocalTransform.FromPosition(spawner.ValueRO.SpawnPosition));
// Resets the next spawn time.
spawner.ValueRW.NextSpawnTime = (float)SystemAPI.Time.ElapsedTime + spawner.ValueRO.SpawnRate;
}
}
}
Next steps
To continue to create and optimize the spawner system, follow the next task in this workflow: