Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active April 8, 2019 05:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tsubaki/c2197d8160109d0109c2dbcbc2537ed7 to your computer and use it in GitHub Desktop.
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;
using Unity.Mathematics;
using Random = Unity.Mathematics.Random;
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 entity = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, World.Active);
var entityManager = World.Active.EntityManager;
entityManager.Instantiate(entity, entities);
Random random = new Random(128);
for (int i = 0; i < count; i++)
{
var pos = new float3(random.NextFloat(-10, 10), random.NextFloat(-10, 10), 0);
entityManager.SetComponentData(entities[i], new Translation() { Value = pos });
}
World.Active.EntityManager.DestroyEntity(entity);
entities.Dispose();
}
void OnDestroy()
{
}
}
using Unity.Entities;
using Unity.Jobs;
using Unity.Transforms;
using UnityEngine;
using Unity.Mathematics;
class RangeCheckSystem : JobComponentSystem
{
EntityCommandBufferSystem barrier; // ------------------- 1
EntityQuery query;
protected override void OnCreate()
{
base.OnCreate();
barrier = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
query = GetEntityQuery(ComponentType.ReadOnly<Translation>());
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
inputDeps = new RangeCheckJob
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * 10),
commandBuffer = barrier.CreateCommandBuffer(), // -------------- 2
}.ScheduleSingle(this, inputDeps);
barrier.AddJobHandleForProducer(inputDeps);
return inputDeps;
}
[Unity.Burst.BurstCompile]
struct RangeCheckJob : IJobForEachWithEntity<Translation>
{
public int Length;
public Vector3 mousePosition;
public EntityCommandBuffer commandBuffer; // ------------------ 3
public void Execute(Entity entity, int index, ref Translation position)
{
if( math.distance(position.Value, mousePosition) < 1)
{
commandBuffer.DestroyEntity(entity);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment