private void Awake() { Instance = this; EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; EntityArchetype boidArchetype = entityManager.CreateArchetype( typeof(BoidECSJobs), typeof(RenderMesh), typeof(RenderBounds), typeof(LocalToWorld) ); NativeArray <Entity> boidArray = new NativeArray <Entity>(boidAmount, Allocator.Temp); entityManager.CreateEntity(boidArchetype, boidArray); for (int i = 0; i < boidArray.Length; i++) { Unity.Mathematics.Random rand = new Unity.Mathematics.Random((uint)i + 1); entityManager.SetComponentData(boidArray[i], new LocalToWorld { Value = float4x4.TRS( RandomPosition(), RandomRotation(), new float3(1f)) }); entityManager.SetSharedComponentData(boidArray[i], new RenderMesh { mesh = sharedMesh, material = sharedMaterial, }); } boidArray.Dispose(); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { // This runs only if there exists a BoidControllerECSJobs instance. if (!controller) { controller = BoidControllerECSJobs.Instance; } if (controller) { EntityQuery boidQuery = GetEntityQuery(ComponentType.ReadOnly <BoidECSJobs>(), ComponentType.ReadOnly <LocalToWorld>()); NativeArray <Entity> entityArray = boidQuery.ToEntityArray(Allocator.TempJob); NativeArray <LocalToWorld> localToWorldArray = boidQuery.ToComponentDataArray <LocalToWorld>(Allocator.TempJob); // These arrays get deallocated after job completion NativeArray <EntityWithLocalToWorld> boidArray = new NativeArray <EntityWithLocalToWorld>(entityArray.Length, Allocator.TempJob); NativeArray <float4x4> newBoidTransforms = new NativeArray <float4x4>(entityArray.Length, Allocator.TempJob); for (int i = 0; i < entityArray.Length; i++) { boidArray[i] = new EntityWithLocalToWorld { entity = entityArray[i], localToWorld = localToWorldArray[i] }; } entityArray.Dispose(); localToWorldArray.Dispose(); BoidJob boidJob = new BoidJob { otherBoids = boidArray, newBoidTransforms = newBoidTransforms, boidPerceptionRadius = controller.boidPerceptionRadius, separationWeight = controller.separationWeight, cohesionWeight = controller.cohesionWeight, alignmentWeight = controller.alignmentWeight, cageSize = controller.cageSize, avoidWallsTurnDist = controller.avoidWallsTurnDist, avoidWallsWeight = controller.avoidWallsWeight, boidSpeed = controller.boidSpeed, deltaTime = Time.DeltaTime }; BoidMoveJob boidMoveJob = new BoidMoveJob { newBoidTransforms = newBoidTransforms }; JobHandle boidJobHandle = boidJob.Schedule(this, inputDeps); return(boidMoveJob.Schedule(this, boidJobHandle)); } else { return(inputDeps); } }