うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】JobSystem を使ってテクスチャを生成してみる

Jobsystem を利用すると処理時間が早くなるということなので、実際にメインスレッドと JobSystem でノイズテクスチャを生成してみました

メインスレッド

    private void CreateTexture(int size)
    {
        var texture = new Texture2D(size, size, TextureFormat.RGBA32, false);
 
        for (var x = 0; x < size; x++)
        {
            for (var y = 0; y < size; y++)
            {
                var noise = Unity.Mathematics.noise.cnoise(new float2(x, y) * 0.01f);
                var v = (byte)Mathf.RoundToInt(noise * 255);
                texture.SetPixel(x, y, new Color32(v, v, v, 255));
            }
        }
 
        texture.Apply();
         
        System.IO.File.WriteAllBytes("Assets/Sample.png", texture.EncodeToPNG());        
    }

JobSystem

    private void CreateTextureByJob(int size)
    {
        var texture = new Texture2D(size, size, TextureFormat.RGBA32, false);
 
        var job = new TextureJob()
        {
            Size = size,
            Pixels = new NativeArray<Color32>(2048 * 2048, Allocator.TempJob),
        };
        var handle = job.Schedule(2048 * 2048, 1);
        handle.Complete();
        
        texture.SetPixelData(job.Pixels, 0);
        texture.Apply();
 
        job.Pixels.Dispose();
         
        System.IO.File.WriteAllBytes("Assets/SampleJob.png", texture.EncodeToPNG());        
    }
 
[BurstCompile]
public struct TextureJob : IJobParallelFor
{
    [ReadOnly]
    public int Size;
    
    [WriteOnly]
    public NativeArray<Color32> Pixels;
    
    public void Execute(int index)
    {
        var x = index % Size;
        var y = index / Size;
        var noise = Unity.Mathematics.noise.cnoise(new float2(x, y) * 0.01f);
        var v = (byte)Mathf.RoundToInt(noise * 255);
        Pixels[index] = new Color32(v, v, v, 255);
    }
}

結果

  • メインスレッド: 5843ms
  • JobSystems: 185ms

メインスレッドに比べて JobSystems は 30倍ほど早く処理することができました