Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Unity.Burst;
  4. using Unity.Collections;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using Unity.Entities;
  7. using Unity.Jobs;
  8. using Unity.Jobs.LowLevel.Unsafe;
  9. using Unity.Transforms;
  10. using UnityEngine;
  11. using Random = Unity.Mathematics.Random;
  12.  
  13. public class SpawnEntitySystem : ComponentSystem
  14. {
  15. private float _nextEntitySpawnTime = 0;
  16.  
  17. private GameObject _ballPrefab;
  18.  
  19. private NativeArray<Random> randoms;
  20.  
  21. protected override void OnCreateManager()
  22. {
  23. _ballPrefab = Resources.Load<GameObject>("Cube");
  24. randoms = new NativeArray<Random>(JobsUtility.MaxJobThreadCount, Allocator.Persistent);
  25. for (var i = 0; i < JobsUtility.MaxJobThreadCount; i++)
  26. randoms[i] = new Random((uint)i + 1);
  27. }
  28.  
  29. protected override void OnDestroyManager()
  30. {
  31. randoms.Dispose();
  32. }
  33.  
  34. protected override void OnUpdate()
  35. {
  36. var state = GetSingleton<GameState>();
  37.  
  38. switch (state.state)
  39. {
  40. case GameState.State.PLAY:
  41. SpawnEntity();
  42. break;
  43. }
  44. }
  45.  
  46. void SpawnEntity()
  47. {
  48. if (Time.timeSinceLevelLoad < _nextEntitySpawnTime)
  49. {
  50. return;
  51. }
  52.  
  53. using (var entities = new NativeArray<Entity>(6, Allocator.TempJob))
  54. {
  55. EntityManager.Instantiate(_ballPrefab, entities);
  56. new InitJob
  57. {
  58. Entities = entities,
  59. Positions = GetComponentDataFromEntity<Position>(),
  60. Randoms = randoms
  61. }.Schedule(entities.Length, 8).Complete();
  62. }
  63.  
  64. _nextEntitySpawnTime = Time.timeSinceLevelLoad + 1;
  65. }
  66.  
  67. //[BurstCompile]
  68. struct InitJob : IJobParallelFor
  69. {
  70. [ReadOnly]
  71. public NativeArray<Entity> Entities;
  72.  
  73. [NativeDisableParallelForRestriction]
  74. public ComponentDataFromEntity<Position> Positions;
  75.  
  76. [NativeDisableParallelForRestriction]
  77. public NativeArray<Random> Randoms;
  78.  
  79. [NativeSetThreadIndex] private int ThreadIndex;
  80.  
  81. public void Execute(int index)
  82. {
  83. var random = Randoms[ThreadIndex];
  84. var pos = Positions[Entities[index]];
  85. pos.Value.y = 15;
  86. pos.Value.x = random.NextFloat(-5f, 5f);
  87. Randoms[ThreadIndex] = random;
  88. Positions[Entities[index]] = pos;
  89. }
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement