forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpawnSystem.cs
More file actions
50 lines (42 loc) · 1.92 KB
/
Copy pathSpawnSystem.cs
File metadata and controls
50 lines (42 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
namespace HelloCube.Prefabs
{
public partial struct SpawnSystem : ISystem
{
uint updateCounter;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
// This call makes the system not update unless at least one entity in the world exists that has the Spawner component.
state.RequireForUpdate<Spawner>();
state.RequireForUpdate<ExecutePrefabs>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
// Create a query that matches all entities having a RotationSpeed component.
// (The query is cached in source generation, so this does not incur a cost of recreating it every update.)
var spinningCubesQuery = SystemAPI.QueryBuilder().WithAll<RotationSpeed>().Build();
// Only spawn cubes when no cubes currently exist.
if (spinningCubesQuery.IsEmpty)
{
var prefab = SystemAPI.GetSingleton<Spawner>().Prefab;
// Instantiating an entity creates copy entities with the same component types and values.
var instances = state.EntityManager.Instantiate(prefab, 500, Allocator.Temp);
// Unlike new Random(), CreateFromIndex() hashes the random seed
// so that similar seeds don't produce similar results.
var random = Random.CreateFromIndex(updateCounter++);
foreach (var entity in instances)
{
// Update the entity's LocalTransform component with the new position.
var transform = SystemAPI.GetComponentRW<LocalTransform>(entity);
transform.ValueRW.Position = (random.NextFloat3() - new float3(0.5f, 0, 0.5f)) * 20;
}
}
}
}
}