Allow setting mesh arrays with NativeArrays.

You can actually modify arrays (int[ ] and Vector3[ ] etc) within jobs using pointers. This is not great but at the moment it’s the best work around to avoid the slow copy (a magnitude of performance increase.)

keijiro has an example of github: GitHub - keijiro/Firefly: Unity ECS example for special effects

The general idea is this

        [BurstCompile]
        private struct GenerateMeshJob : IJob
        {
            // ...

            // basically a wrapper for a int pointer, from https://github.com/keijiro/Firefly
            public NativeCounter.Concurrent Counter;

            // Pointers to the start of an array
            [NativeDisableUnsafePtrRestriction] public void* Vertices;

            public void Execute()
            {
                // ...
                UnsafeUtility.WriteArrayElement(Vertices, vertCount + n, vertices);
                // ...
            }
        }
 
        // Job creation
        var generateMeshJob = new GenerateMeshJob
        {
            Vertices = UnsafeUtility.AddressOf(ref vertices[0]),
        }
        .Schedule(getVisibleFacesJob);

From this I figured out you can actually do it for Lists as well (using the internal array lists hold) which I needed because I wanted to use the SetUV(List).

This is a little more complicated as it’s either super slow or creates garbage if you’re not careful. I was intending to write a blog post / tutorial on doing all this later this week.

I’ve managed to get a nice voxel engine running generating meshes for 400k voxels in 2.8ms on an older 3570k. It takes 4x longer to upload the changed mesh to the GPU than it does to generate it.

6 Likes