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
70 lines (59 loc) · 2.17 KB
/
Copy pathSpawnSystem.cs
File metadata and controls
70 lines (59 loc) · 2.17 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Random = Unity.Mathematics.Random;
namespace HelloCube.RandomSpawn
{
public partial struct SpawnSystem : ISystem
{
uint seedOffset;
float spawnTimer;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<Config>();
state.RequireForUpdate<ExecuteRandomSpawn>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
const int count = 200;
const float spawnWait = 0.05f; // 0.05 seconds
spawnTimer -= SystemAPI.Time.DeltaTime;
if (spawnTimer > 0)
{
return;
}
spawnTimer = spawnWait;
// Remove the NewSpawn tag component from the entities spawned in the prior frame.
var newSpawnQuery = SystemAPI.QueryBuilder().WithAll<NewSpawn>().Build();
state.EntityManager.RemoveComponent<NewSpawn>(newSpawnQuery);
// Spawn the boxes
var prefab = SystemAPI.GetSingleton<Config>().Prefab;
state.EntityManager.Instantiate(prefab, count, Allocator.Temp);
// Every spawned box needs a unique seed, so the
// seedOffset must be incremented by the number of boxes every frame.
seedOffset += count;
new RandomPositionJob
{
SeedOffset = seedOffset
}.ScheduleParallel();
}
}
[WithAll(typeof(NewSpawn))]
[BurstCompile]
partial struct RandomPositionJob : IJobEntity
{
public uint SeedOffset;
public void Execute([EntityIndexInQuery] int index, ref LocalTransform transform)
{
// Random instances with similar seeds produce similar results, so to get proper
// randomness here, we use CreateFromIndex, which hashes the seed.
var random = Random.CreateFromIndex(SeedOffset + (uint)index);
var xz = random.NextFloat2Direction() * 50;
transform.Position = new float3(xz[0], 50, xz[1]);
}
}
}