Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;
using Unity.Mathematics;
public class GameController : MonoBehaviour
{
[SerializeField] GameObject prefab;
NativeArray<Entity> entities;
const int count = 4000;
void Awake ()
{
entities = new NativeArray<Entity>(count, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
var entityManager = World.Active.GetOrCreateManager<EntityManager>();
entityManager.Instantiate(prefab, entities);
for (int i = 0; i < count; i++)
{
var pos = new float3(Random.Range(-10f, 10f), Random.Range(-10f, 10f), 0);
entityManager.SetComponentData(entities[i], new Position() { Value = pos});
}
}
void OnDestroy()
{
entities.Dispose();
}
}
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Transforms;
using Unity.Rendering;
using UnityEngine;
using Unity.Mathematics;
[UpdateAfter(typeof(MeshInstanceRendererSystem))]
class RangeCheckSystem : JobComponentSystem
{
struct Group
{
public int Length;
[ReadOnly] public ComponentDataArray<Position> positions;
[ReadOnly] public EntityArray entityArrays;
}
[Inject] EndFrameBarrier barrier; // ------------------- 1
[Inject] Group group;
protected override JobHandle OnUpdate(JobHandle inputDeps) => new RangeCheckJob()
{
Length = group.Length,
position = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * 10),
commandBuffer = barrier.CreateCommandBuffer(), // -------------- 2
positions = group.positions,
entityArrays = group.entityArrays,
}.Schedule(inputDeps);
[Unity.Burst.BurstCompile]
struct RangeCheckJob : IJob
{
public int Length;
public Vector3 position;
public EntityCommandBuffer commandBuffer; // ------------------ 3
[ReadOnly] public EntityArray entityArrays;
[ReadOnly] public ComponentDataArray<Position> positions;
public void Execute()
{
for(int i=0; i<Length; i++)
{
if( math.distance( positions[i].Value, position) < 1)
{
commandBuffer.DestroyEntity(entityArrays[i]); // ----------- 4
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment