Created
          February 11, 2019 13:02 
        
      - 
      
 - 
        
Save simonwittber/8e9582f2fc3f3aa9040beeedb550074c to your computer and use it in GitHub Desktop.  
    Instance Rendering Helper
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | public class InstancedRenderer : System.IDisposable | |
| { | |
| const int BATCH_MAX = 1023; | |
| public NativeArray<Matrix4x4> matrices; | |
| public readonly int count, allocated; | |
| public readonly Mesh mesh; | |
| public readonly Material material; | |
| Matrix4x4[] batchedMatrices = new Matrix4x4[BATCH_MAX]; | |
| public void Dispose() | |
| { | |
| matrices.Dispose(); | |
| } | |
| public InstancedRenderer(int count, Mesh mesh, Material material) | |
| { | |
| this.count = count; | |
| this.mesh = mesh; | |
| this.material = material; | |
| var remainder = count % BATCH_MAX; | |
| allocated = remainder == 0 ? count : count + BATCH_MAX - remainder; | |
| matrices = new NativeArray<Matrix4x4>(allocated, Allocator.Persistent); | |
| for (int i = 0; i < count; ++i) | |
| matrices[i] = Matrix4x4.identity; | |
| } | |
| public void Render(int submeshIndex = 0) | |
| { | |
| int batches = Mathf.CeilToInt(count / BATCH_MAX); | |
| for (int i = 0; i < batches; ++i) | |
| { | |
| int batchCount = Mathf.Min(1023, count - (BATCH_MAX * i)); | |
| int start = Mathf.Max(0, (i - 1) * BATCH_MAX); | |
| matrices.Slice(start, batchCount).CopyTo(batchedMatrices); | |
| Graphics.DrawMeshInstanced(mesh, submeshIndex, material, batchedMatrices, batchCount); | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment