Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Unity.Collections;
- using Unity.Entities;
- using Unity.Jobs;
- using Unity.Mathematics;
- using Unity.Transforms;
- using UnityEngine;
- using Random = Unity.Mathematics.Random;
- [UpdateInGroup(typeof(SimulationSystemGroup))]
- public class ShipSpawnerSys : JobComponentSystem
- {
- private const int MaxShips = 20000;
- private const float SpawnRatePerSecond = 1000;
- private Random rand;
- private int shipCount;
- private BeginInitializationEntityCommandBufferSystem cmdBufferSystem;
- protected override void OnCreate()
- {
- rand = new Random(1);
- shipCount = 0;
- cmdBufferSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
- }
- private struct SpawnJob : IJobForEachWithEntity<ShipSpawner, LocalToWorld, Rotation>
- {
- public EntityCommandBuffer CommandBuffer;
- //public uint RandSeedOffset;
- public Random Rand;
- public float Time;
- public float Dt;
- public int SpawnCount;
- public void Execute(Entity entity, int index, [ReadOnly] ref ShipSpawner spawner, [ReadOnly] ref LocalToWorld location, [ReadOnly] ref Rotation rotation)
- {
- //Random rand = new Random((uint)((index + RandSeedOffset) % uint.MaxValue));
- for (int i = 0; i < SpawnCount; i++)
- {
- Entity ship = CommandBuffer.Instantiate(spawner.Prefab);
- float3 pos = math.transform(location.Value, new float3(Rand.NextFloat(-500f, 500f), 0, Rand.NextFloat(-20f, 20f)));
- CommandBuffer.SetComponent(ship, new Rotation { Value = rotation.Value });
- CommandBuffer.AddComponent(ship, new Velocity());
- CommandBuffer.SetComponent(ship, new Translation { Value = pos });
- CommandBuffer.AddComponent(ship, new SpawnTime { Value = Time });
- }
- }
- }
- protected override JobHandle OnUpdate(JobHandle inputDeps)
- {
- int maxToSpawn = MaxShips - shipCount;
- int spawnCount = math.min((int)(SpawnRatePerSecond * Time.deltaTime), maxToSpawn);
- shipCount += spawnCount;
- // Schedule the job that will add Instantiate commands to the EntityCommandBuffer.
- var job = new SpawnJob
- {
- CommandBuffer = cmdBufferSystem.CreateCommandBuffer(),
- //RandSeedOffset = rand.NextUInt(),
- Rand = rand,
- Time = Time.time,
- Dt = Time.deltaTime,
- SpawnCount = spawnCount,
- }.ScheduleSingle(this, inputDeps);
- // SpawnJob runs in parallel with no sync point until the barrier system executes.
- // When the barrier system executes we want to complete the SpawnJob and then play back the commands (Creating the entities and placing them).
- // We need to tell the barrier system which job it needs to complete before it can play back the commands.
- cmdBufferSystem.AddJobHandleForProducer(job);
- return job;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement