Last active
April 10, 2021 02:02
-
-
Save d12/e380c85a096444dc8669b9b6a64828d7 to your computer and use it in GitHub Desktop.
When using GPU instancing on a small number of unique meshes, it helps to have all objects with a specific mesh on the same render queue so that GPU instancing can properly batch all objects together. Otherwise, you end up with a semi-shuffled render queue and the GPU instancing algorithm won't batch draws that aren't back-to-back. RenderQueueSo…
This file contains 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 static class RenderQueueSorter | |
{ | |
private static int nextRenderQueue = 5; // Don't go over 2500! Or we leak into transparent queues | |
private static Dictionary<Mesh, Material> _meshToMatMap = new Dictionary<Mesh, Material>(); | |
public static Material SortedMaterialFromMesh(Mesh mesh, Material sharedMaterial) | |
{ | |
if (_meshToMatMap.ContainsKey(mesh)) return _meshToMatMap[mesh]; | |
return GenerateMaterialForMesh(mesh, sharedMaterial); | |
} | |
private static Material GenerateMaterialForMesh(Mesh mesh, Material sharedMaterial) | |
{ | |
Material newMaterial = new Material(sharedMaterial); | |
newMaterial.renderQueue = nextRenderQueue; | |
nextRenderQueue += 1; | |
_meshToMatMap[mesh] = newMaterial; | |
return newMaterial; | |
} | |
} |
This file contains 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
private void Awake() { | |
... | |
SetSortedMaterial(); | |
} | |
private void SetSortedMaterial() { | |
MeshFilter meshFilter = GetComponent<MeshFilter>(); | |
MeshRenderer meshRenderer = GetComponent<MeshRenderer>(); | |
meshRenderer.material = RenderQueueSorter.SortedMaterialFromMesh(meshFilter.sharedMesh, meshRenderer.sharedMaterial); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment