Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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];
}
}
}
@tsubaki

This comment has been minimized.

Copy link
Owner Author

tsubaki commented Nov 14, 2018

23 30 48

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.