Skip to content

Instantly share code, notes, and snippets.

@EricHu33
Last active December 5, 2022 05:43
Show Gist options
  • Save EricHu33/2e754abf505ca7ed2a3a85eb557c1ae0 to your computer and use it in GitHub Desktop.
Save EricHu33/2e754abf505ca7ed2a3a85eb557c1ae0 to your computer and use it in GitHub Desktop.
async and burst direct call test
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;
using Unity.Burst;
using UnityEngine.Profiling;
using Unity.Collections;
using UnityEngine.UI;
using System.Threading.Tasks;
[BurstCompile(Debug = true)]
public class TestController : MonoBehaviour
{
[SerializeField] int _size = 256;
[SerializeField] RawImage _target = null;
Texture2D _texture;
// Start is called before the first frame update
void Start()
{
_texture = new Texture2D(_size, _size, TextureFormat.RGBA32, false);
_target.texture = _texture;
}
private async void PerformNoise()
{
Debug.Log("async prepare task.....");
var delayTask = Task.Delay(1000);
var task1 = noiseTask();
await Task.WhenAll(delayTask, task1);
Debug.Log("noise task done");
}
private Task noiseTask()
{
Profiler.BeginSample("Texture Generation");
using var temp = new NativeArray<uint>(_size * _size, Allocator.Temp);
var buffer = new NativeSlice<uint>(temp);
var time = Time.time;
var offs = 0;
for (var y = 0; y < _size; y++)
for (var x = 0; x < _size; x++)
buffer[offs++] = GetPixel(x, y, time);
Profiler.EndSample();
_texture.LoadRawTextureData(temp);
_texture.Apply();
return Task.CompletedTask;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
PerformNoise();
}
transform.position += new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0) * 15f * Time.deltaTime;
}
[BurstCompile]
public static uint GetPixel(int x, int y, float t)
{
var pos = math.float3(x, y, t) * math.float3(0.008f, 0.008f, 0.5f);
var f32 = noise.snoise(pos) * 0.4f + 0.5f;
var un8 = (uint)(math.saturate(f32) * 255);
return un8 | un8 << 8 | un8 << 16 | 0xff000000;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment