Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using Unity.Burst;
- using Unity.Collections;
- using Unity.Collections.LowLevel.Unsafe;
- using Unity.Entities;
- using Unity.Jobs;
- using Unity.Jobs.LowLevel.Unsafe;
- using Unity.Transforms;
- using UnityEngine;
- using Random = Unity.Mathematics.Random;
- public class SpawnEntitySystem : ComponentSystem
- {
- private float _nextEntitySpawnTime = 0;
- private GameObject _ballPrefab;
- private NativeArray<Random> randoms;
- protected override void OnCreateManager()
- {
- _ballPrefab = Resources.Load<GameObject>("Cube");
- randoms = new NativeArray<Random>(JobsUtility.MaxJobThreadCount, Allocator.Persistent);
- for (var i = 0; i < JobsUtility.MaxJobThreadCount; i++)
- randoms[i] = new Random((uint)i + 1);
- }
- protected override void OnDestroyManager()
- {
- randoms.Dispose();
- }
- protected override void OnUpdate()
- {
- var state = GetSingleton<GameState>();
- switch (state.state)
- {
- case GameState.State.PLAY:
- SpawnEntity();
- break;
- }
- }
- void SpawnEntity()
- {
- if (Time.timeSinceLevelLoad < _nextEntitySpawnTime)
- {
- return;
- }
- using (var entities = new NativeArray<Entity>(6, Allocator.TempJob))
- {
- EntityManager.Instantiate(_ballPrefab, entities);
- new InitJob
- {
- Entities = entities,
- Positions = GetComponentDataFromEntity<Position>(),
- Randoms = randoms
- }.Schedule(entities.Length, 8).Complete();
- }
- _nextEntitySpawnTime = Time.timeSinceLevelLoad + 1;
- }
- //[BurstCompile]
- struct InitJob : IJobParallelFor
- {
- [ReadOnly]
- public NativeArray<Entity> Entities;
- [NativeDisableParallelForRestriction]
- public ComponentDataFromEntity<Position> Positions;
- [NativeDisableParallelForRestriction]
- public NativeArray<Random> Randoms;
- [NativeSetThreadIndex] private int ThreadIndex;
- public void Execute(int index)
- {
- var random = Randoms[ThreadIndex];
- var pos = Positions[Entities[index]];
- pos.Value.y = 15;
- pos.Value.x = random.NextFloat(-5f, 5f);
- Randoms[ThreadIndex] = random;
- Positions[Entities[index]] = pos;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement