Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using Unity.Entities;
using Unity.Transforms;
using Unity.Collections;
using Unity.Mathematics;
using Unity.Jobs;
public class NewComponentDataArrayWithJobSampleSystem : JobComponentSystem
{
ComponentGroup playerGroup, enemyGroup;
protected override void OnCreateManager()
{
// コンポーネントの準備
playerGroup = GetComponentGroup(
ComponentType.ReadOnly<Position>(),
ComponentType.ReadOnly<Player>(),
ComponentType.Create<HitPoint>());
enemyGroup = GetComponentGroup(
ComponentType.ReadOnly<Position>(),
ComponentType.ReadOnly<Enemy>());
RequireForUpdate(playerGroup);
RequireForUpdate(enemyGroup);
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
playerGroup.AddDependency(inputDeps);
// チャンクからNativeArrayを取得
// JobHandleを指定しないと即Completeしてしまうので、JobHandleを設定して、並列で一気に取得できるようにする
var playerPositions = playerGroup.ToComponentDataArray<Position>(Allocator.TempJob, out JobHandle handle1);
var playerHitpoint = playerGroup.ToComponentDataArray<HitPoint>(Allocator.TempJob, out JobHandle handle2);
var enemyPositions = enemyGroup.ToComponentDataArray<Position>(Allocator.TempJob, out JobHandle handle3);
inputDeps = JobHandle.CombineDependencies(handle1, handle2, handle3);
// 当たり判定処理
inputDeps = new PlayerHitcheck
{
playerPositions = playerPositions,
enemyPositions = enemyPositions,
playerHitpoint = playerHitpoint
}.Schedule(playerGroup.CalculateLength(), 32, inputDeps);
// ダメージを反映
// PlayerHitcheckのジョブと依存関係を持つ為にAddDependencyを設定
playerGroup.AddDependency(inputDeps);
playerGroup.CopyFromComponentDataArray(playerHitpoint, out JobHandle handle4);
// NativeArrayを破棄
inputDeps = new ReleaseJob
{
playerHitpoint = playerHitpoint
}.Schedule(handle4);
return inputDeps;
}
struct ReleaseJob : IJob
{
[DeallocateOnJobCompletion]
public NativeArray<HitPoint> playerHitpoint;
public void Execute(){}
}
struct PlayerHitcheck : IJobParallelFor
{
[ReadOnly]
[DeallocateOnJobCompletion]
public NativeArray<Position> playerPositions;
[ReadOnly]
[DeallocateOnJobCompletion]
public NativeArray<Position> enemyPositions;
public NativeArray<HitPoint> playerHitpoint;
public void Execute(int index)
{
for(int i=0; i<enemyPositions.Length; i++)
{
if( math.distance( playerPositions[index].Value, enemyPositions[i].Value) < 1)
{
var hitpoint = playerHitpoint[index];
hitpoint.Value -= 1;
playerHitpoint[index] = hitpoint;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.