Skip to content

Instantly share code, notes, and snippets.

@baobao
Created September 9, 2018 14:42
Show Gist options
  • Save baobao/7122c80b272d68bd70d4d9b6375ade4d to your computer and use it in GitHub Desktop.
Save baobao/7122c80b272d68bd70d4d9b6375ade4d to your computer and use it in GitHub Desktop.
using UnityEngine;
using Unity.Collections;
using Unity.Jobs;
/// <summary>
/// 毎フレームpositionにvelocityを加算するだけの単純なジョブサンプル
/// </summary>
public class ApplyVelocitySample : MonoBehaviour
{
/// <summary>
/// ジョブ定義
/// 定義できる変数はBlittable型のみ
/// </summary>
struct VelocityJob : IJob
{
[ReadOnly]
public NativeArray<Vector3> velocity;
public NativeArray<Vector3> position;
public float deltaTime;
/// <summary>
/// ジョブの処理内容
/// </summary>
public void Execute()
{
for (var i = 0; i < position.Length; i++)
{
position[i] = position[i] + velocity[i] * deltaTime;
}
}
}
/// <summary>
/// 処理する要素数
/// </summary>
private int _count = 10000;
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);
}
// ジョブ生成して、必要情報を渡す
var job = new VelocityJob()
{
deltaTime = Time.deltaTime,
position = position,
velocity = velocity
};
// ジョブを実行
JobHandle jobHandle = job.Schedule();
// ジョブ完了の待機
jobHandle.Complete();
for (int i = 0; i < _count; i++)
{
// ジョブから更新後のデータを取得してほげほげする
var pos = job.position[i];
// Do something...
}
// バッファの破棄
position.Dispose();
velocity.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment