Skip to content

Instantly share code, notes, and snippets.

@TJHeuvel
Created April 4, 2023 12:16
Show Gist options
  • Save TJHeuvel/f99edeb7044bd05ba1652ee473cf778e to your computer and use it in GitHub Desktop.
Save TJHeuvel/f99edeb7044bd05ba1652ee473cf778e to your computer and use it in GitHub Desktop.
DrawInstancedCustomCB
class DrawInstancedCustomCB : MonoBehaviour
{
[SerializeField] private Mesh mesh;
[SerializeField] private Material mat;
private MaterialPropertyBlock propBlock;
private GraphicsBuffer objectToWorlds;
void Start()
{
Random.InitState(123);
objectToWorlds = new GraphicsBuffer(GraphicsBuffer.Target.Constant, GraphicsBuffer.UsageFlags.LockBufferForWrite, 1023, UnsafeUtility.SizeOf<Matrix4x4>());
var buffer = objectToWorlds.LockBufferForWrite<Matrix4x4>(0, objectToWorlds.count);
for (int i = 0; i < objectToWorlds.count; i++)
buffer[i] = Matrix4x4.TRS(new Vector3(Random.Range(-100, 100), Random.Range(-20, 20), Random.Range(-100, 100)), Quaternion.identity, Vector3.one);
objectToWorlds.UnlockBufferAfterWrite<Matrix4x4>(1023);
propBlock = new MaterialPropertyBlock();
propBlock.SetConstantBuffer("UnityInstancing_PerDraw0", objectToWorlds, 0, objectToWorlds.count * objectToWorlds.stride);
}
void Update()
{
mat.enabledKeywords = new UnityEngine.Rendering.LocalKeyword[] { new UnityEngine.Rendering.LocalKeyword(mat.shader, "INSTANCING_ON") };
Graphics.RenderMeshPrimitives(new RenderParams(mat) { matProps = propBlock }, mesh, 0, objectToWorlds.count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment