Skip to content

Instantly share code, notes, and snippets.

@baobao
Last active December 7, 2018 02:43
Show Gist options
  • Save baobao/2bb746ae7e27355c20b01db362878770 to your computer and use it in GitHub Desktop.
Save baobao/2bb746ae7e27355c20b01db362878770 to your computer and use it in GitHub Desktop.
ジョブの使用/未使用を切り替えてみた
using UnityEngine;
using Unity.Collections;
using Unity.Jobs;
/// <summary>
/// 毎フレームpositionにvelocityを加算するだけの単純なジョブサンプル
/// </summary>
public class ApplyVelocitySample2 : MonoBehaviour
{
/// <summary>
/// ジョブ定義
/// 定義できる変数はBlittable型のみ
/// </summary>
struct VelocityJob : IJob
{
[ReadOnly]
public NativeArray<Vector3> velocity;
public NativeArray<Vector3> position;
public float deltaTime;
/// <summary>
/// ジョブの処理内容
/// </summary>
public void Execute()
{
Utility.Execute(position, velocity, deltaTime);
}
}
/// <summary>
/// 処理する要素数
/// </summary>
private int _count = 100000;
public bool useJob = false;
public void Update()
{
// バッファ生成
var position = new NativeArray<Vector3>(_count, Allocator.Persistent);
var velocity = new NativeArray<Vector3>(_count, Allocator.Persistent);
for (var i = 0; i < velocity.Length; i++)
{
// 入力バッファの中身を詰める
velocity[i] = new Vector3(0, 10, 0);
}
if (useJob)
{
// ジョブ生成して、必要情報を渡す
var job = new VelocityJob()
{
deltaTime = Time.deltaTime,
position = position,
velocity = velocity
};
// ジョブを実行
JobHandle jobHandle = job.Schedule();
// ジョブ完了の待機
jobHandle.Complete();
}
else
{
Utility.Execute(position, velocity, Time.deltaTime);
}
for (int i = 0; i < _count; i++)
{
// 更新後のデータを取得してほげほげする
var pos = position[i];
// Do something...
}
// バッファの破棄
position.Dispose();
velocity.Dispose();
}
}
public static class Utility
{
public static void Execute(NativeArray<Vector3> position, NativeArray<Vector3> velocity, float deltaTime)
{
for (var i = 0; i < position.Length; i++)
{
position[i] = position[i] + velocity[i] * deltaTime;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment