Created
November 14, 2018 14:33
-
-
Save tsubaki/90872602072a6c94fc1d6b0fad39faa2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.Jobs; | |
using Unity.Jobs; | |
using Unity.Mathematics; | |
using Unity.Collections; | |
public class TransformAccessSample2 : MonoBehaviour | |
{ | |
[SerializeField] private Transform parent; | |
private TransformAccessArray transforms; | |
private JobHandle handle; | |
void OnEnable() | |
{ | |
transforms = new TransformAccessArray(parent.GetComponentsInChildren<Transform>(), 1); | |
transforms.RemoveAtSwapBack(0); | |
parent.DetachChildren(); | |
} | |
void OnDisable() | |
{ | |
transforms.Dispose(); | |
} | |
void Update() | |
{ | |
handle.Complete(); | |
NativeArray<Vector3> positions = new NativeArray<Vector3>(transforms.length, Allocator.TempJob); | |
handle = new CopyFromTransform(positions).Schedule(transforms, handle); | |
handle = new NoiseJob(positions, Time.timeSinceLevelLoad).Schedule(transforms.length, 64, handle); | |
handle = new ApplyTransform(positions).Schedule(transforms, handle); | |
JobHandle.ScheduleBatchedJobs(); | |
} | |
//[Unity.Burst.BurstCompile] | |
struct CopyFromTransform : IJobParallelForTransform | |
{ | |
private NativeArray<Vector3> positions; | |
public CopyFromTransform(NativeArray<Vector3> positions) | |
{ | |
this.positions = positions; | |
} | |
public void Execute(int index, TransformAccess transform) | |
{ | |
positions[index] = transform.position; | |
} | |
} | |
//[Unity.Burst.BurstCompile] | |
struct NoiseJob : IJobParallelFor | |
{ | |
private NativeArray<Vector3> positions; | |
private float offset; | |
const float height = 1; | |
const float per = 128; | |
const float size = 0.05f; | |
public NoiseJob(NativeArray<Vector3> positions, float offset) | |
{ | |
this.positions = positions; | |
this.offset = offset; | |
} | |
public void Execute(int index) | |
{ | |
Vector3 pos = positions[index]; | |
float x = pos.x * 0.2f + offset; | |
float z = pos.z * 0.2f + offset; | |
float2 noisePos = new float2(x, z); | |
pos.y = noise.psrnoise(noisePos, new float2(per, per)) * height; | |
positions[index] = pos; | |
} | |
} | |
//[Unity.Burst.BurstCompile] | |
struct ApplyTransform : IJobParallelForTransform | |
{ | |
[DeallocateOnJobCompletion] | |
private NativeArray<Vector3> positions; | |
public ApplyTransform(NativeArray<Vector3> positions) | |
{ | |
this.positions = positions; | |
} | |
public void Execute(int index, TransformAccess transform) | |
{ | |
transform.position = positions[index]; | |
} | |
} | |
} |
Author
tsubaki
commented
Nov 14, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment