Documentation

Unity Engine

Download Unity

Unity Engine

DrawMeshInstancedIndirect

This function is now obsolete. Use Graphics.RenderMeshIndirect instead. Draws the same mesh multiple times using GPU instancing.
Read time 10 minutesLast updated 2 days ago

Definition

  • Type: Method
  • Namespace: UnityEngine
  • Assembly: UnityEngine.CoreModule

DrawMeshInstancedIndirect(Mesh, int, Material, Bounds, ComputeBuffer, int, MaterialPropertyBlock, ShadowCastingMode, bool, int, Camera, LightProbeUsage)

This function is now obsolete. Use Graphics.RenderMeshIndirect instead. Draws the same mesh multiple times using GPU instancing.
public static void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, Bounds bounds, ComputeBuffer bufferWithArgs, int argsOffset = 0, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0, Camera camera = null, LightProbeUsage lightProbeUsage = LightProbeUsage.BlendProbes)

Parameters

mesh

The Mesh to draw.

submeshIndex

Which subset of the mesh to draw. This applies only to meshes that are composed of several materials.

material

Material to use.

bounds

The bounding volume surrounding the instances you intend to draw.

bufferWithArgs

The GPU buffer containing the arguments for how many instances of this mesh to draw.

argsOffset

The byte offset into the buffer, where the draw arguments start.

Additional material properties to apply. See MaterialPropertyBlock.

Determines whether the mesh can cast shadows.

receiveShadows

Determines whether the mesh can receive shadows.

layer

Layer to use.

camera

If
null
(default), the mesh will be drawn in all cameras. Otherwise it will be drawn in the given Camera only.

lightProbeUsage

LightProbeUsage for the instances.

Remarks

This function only works on platforms that support compute shaders.
Similar to Graphics.DrawMeshInstanced, this function draws many instances of the same mesh, but unlike that method, the arguments for how many instances to draw come from
bufferWithArgs
.
Use this function in situations where you want to draw the same mesh for a particular amount of times using an instanced shader. Meshes are not further culled by the view frustum or baked occluders, nor sorted for transparency or z efficiency.
Buffer with arguments,
bufferWithArgs
, has to have five integer numbers at given
argsOffset
offset: index count per instance, instance count, start index location, base vertex location, start instance location.
Unity only needs the submeshIndex argument if submeshes within the mesh have different topologies (e.g. Triangles and Lines). Otherwise, all the information about which submesh to draw comes from the bufferWithArgs argument.
Here is a script that can be used to draw many instances of the same mesh:
using UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour { public int instanceCount = 100000; public Mesh instanceMesh; public Material instanceMaterial; public int subMeshIndex = 0; private int cachedInstanceCount = -1; private int cachedSubMeshIndex = -1; private ComputeBuffer positionBuffer; private ComputeBuffer argsBuffer; private uint[] args = new uint[5] { 0, 0, 0, 0, 0 }; void Start() { argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments); UpdateBuffers(); } void Update() { // Update starting position buffer if (cachedInstanceCount != instanceCount || cachedSubMeshIndex != subMeshIndex) UpdateBuffers(); // Pad input if (Input.GetAxisRaw("Horizontal") != 0.0f) instanceCount = (int)Mathf.Clamp(instanceCount + Input.GetAxis("Horizontal") * 40000, 1.0f, 5000000.0f); // Render Graphics.DrawMeshInstancedIndirect(instanceMesh, subMeshIndex, instanceMaterial, new Bounds(Vector3.zero, new Vector3(100.0f, 100.0f, 100.0f)), argsBuffer); } void OnGUI() { GUI.Label(new Rect(265, 25, 200, 30), "Instance Count: " + instanceCount.ToString()); instanceCount = (int)GUI.HorizontalSlider(new Rect(25, 20, 200, 30), (float)instanceCount, 1.0f, 5000000.0f); } void UpdateBuffers() { // Ensure submesh index is in range if (instanceMesh != null) subMeshIndex = Mathf.Clamp(subMeshIndex, 0, instanceMesh.subMeshCount - 1); // Positions if (positionBuffer != null) positionBuffer.Release(); positionBuffer = new ComputeBuffer(instanceCount, 16); Vector4[] positions = new Vector4[instanceCount]; for (int i = 0; i < instanceCount; i++) { float angle = Random.Range(0.0f, Mathf.PI * 2.0f); float distance = Random.Range(20.0f, 100.0f); float height = Random.Range(-2.0f, 2.0f); float size = Random.Range(0.05f, 0.25f); positions[i] = new Vector4(Mathf.Sin(angle) * distance, height, Mathf.Cos(angle) * distance, size); } positionBuffer.SetData(positions); instanceMaterial.SetBuffer("positionBuffer", positionBuffer); // Indirect args if (instanceMesh != null) { args[0] = (uint)instanceMesh.GetIndexCount(subMeshIndex); args[1] = (uint)instanceCount; args[2] = (uint)instanceMesh.GetIndexStart(subMeshIndex); args[3] = (uint)instanceMesh.GetBaseVertex(subMeshIndex); } else { args[0] = args[1] = args[2] = args[3] = 0; } argsBuffer.SetData(args); cachedInstanceCount = instanceCount; cachedSubMeshIndex = subMeshIndex; } void OnDisable() { if (positionBuffer != null) positionBuffer.Release(); positionBuffer = null; if (argsBuffer != null) argsBuffer.Release(); argsBuffer = null; }}
The following Universal Render Pipeline (URP) shader works with the previous example script:
Shader "Instanced/InstancedShader"{ Properties { _BaseMap ("Albedo (RGB)", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" } Pass { Tags { "LightMode"="UniversalForwardOnly" } HLSLPROGRAM #pragma vertex vert #pragma fragment frag #pragma target 4.5 #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" TEXTURE2D(_BaseMap); SAMPLER(sampler_BaseMap); // The position (xyz) and scale (w) of each instance, set by the example script. StructuredBuffer<float4> positionBuffer; struct Attributes { float4 positionOS : POSITION; float3 normalOS : NORMAL; float2 uv : TEXCOORD0; float4 color : COLOR; }; struct Varyings { float4 positionCS : SV_POSITION; float2 uv : TEXCOORD0; float3 ambient : TEXCOORD1; float3 diffuse : TEXCOORD2; float3 color : TEXCOORD3; float3 positionWS : TEXCOORD4; }; // Rotates a 2D vector by r radians. void rotate2D(inout float2 v, float r) { float s, c; sincos(r, s, c); v = float2(v.x * c - v.y * s, v.x * s + v.y * c); } Varyings vert(Attributes v, uint instanceID : SV_InstanceID) { // Get the data for this instance. float4 data = positionBuffer[instanceID]; // Rotate the instance around the origin over time. Larger instances rotate faster. float rotation = data.w * data.w * _Time.x * 0.5f; rotate2D(data.xz, rotation); // Scale the vertex, then move it to the position of the instance. float3 localPosition = v.positionOS.xyz * data.w; float3 worldPosition = data.xyz + localPosition; float3 worldNormal = v.normalOS; // Calculate simple diffuse lighting from the main light, and ambient lighting from light probes. Light mainLight = GetMainLight(); float ndotl = saturate(dot(worldNormal, mainLight.direction)); Varyings o; o.positionCS = TransformWorldToHClip(worldPosition); o.uv = v.uv; o.ambient = SampleSH(worldNormal); o.diffuse = ndotl * mainLight.color; o.color = v.color.rgb; o.positionWS = worldPosition; return o; } half4 frag(Varyings i) : SV_Target { // Apply the shadows of the main light to the diffuse lighting only. float shadow = MainLightRealtimeShadow(TransformWorldToShadowCoord(i.positionWS)); half4 albedo = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, i.uv); float3 lighting = i.diffuse * shadow + i.ambient; return half4(albedo.rgb * i.color * lighting, albedo.a); } ENDHLSL } }}

DrawMeshInstancedIndirect(Mesh, int, Material, Bounds, GraphicsBuffer, int, MaterialPropertyBlock, ShadowCastingMode, bool, int, Camera, LightProbeUsage)

This function is now obsolete. Use Graphics.RenderMeshIndirect instead. Draws the same mesh multiple times using GPU instancing.
public static void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, Bounds bounds, GraphicsBuffer bufferWithArgs, int argsOffset = 0, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0, Camera camera = null, LightProbeUsage lightProbeUsage = LightProbeUsage.BlendProbes)

Parameters

mesh

The Mesh to draw.

submeshIndex

Which subset of the mesh to draw. This applies only to meshes that are composed of several materials.

material

Material to use.

bounds

The bounding volume surrounding the instances you intend to draw.

bufferWithArgs

The GPU buffer containing the arguments for how many instances of this mesh to draw.

argsOffset

The byte offset into the buffer, where the draw arguments start.

Additional material properties to apply. See MaterialPropertyBlock.

Determines whether the mesh can cast shadows.

receiveShadows

Determines whether the mesh can receive shadows.

layer

Layer to use.

camera

If
null
(default), the mesh will be drawn in all cameras. Otherwise it will be drawn in the given Camera only.

lightProbeUsage

LightProbeUsage for the instances.

Remarks

This function only works on platforms that support compute shaders.
Similar to Graphics.DrawMeshInstanced, this function draws many instances of the same mesh, but unlike that method, the arguments for how many instances to draw come from
bufferWithArgs
.
Use this function in situations where you want to draw the same mesh for a particular amount of times using an instanced shader. Meshes are not further culled by the view frustum or baked occluders, nor sorted for transparency or z efficiency.
Buffer with arguments,
bufferWithArgs
, has to have five integer numbers at given
argsOffset
offset: index count per instance, instance count, start index location, base vertex location, start instance location.
Unity only needs the submeshIndex argument if submeshes within the mesh have different topologies (e.g. Triangles and Lines). Otherwise, all the information about which submesh to draw comes from the bufferWithArgs argument.
Here is a script that can be used to draw many instances of the same mesh:
using UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour { public int instanceCount = 100000; public Mesh instanceMesh; public Material instanceMaterial; public int subMeshIndex = 0; private int cachedInstanceCount = -1; private int cachedSubMeshIndex = -1; private ComputeBuffer positionBuffer; private ComputeBuffer argsBuffer; private uint[] args = new uint[5] { 0, 0, 0, 0, 0 }; void Start() { argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments); UpdateBuffers(); } void Update() { // Update starting position buffer if (cachedInstanceCount != instanceCount || cachedSubMeshIndex != subMeshIndex) UpdateBuffers(); // Pad input if (Input.GetAxisRaw("Horizontal") != 0.0f) instanceCount = (int)Mathf.Clamp(instanceCount + Input.GetAxis("Horizontal") * 40000, 1.0f, 5000000.0f); // Render Graphics.DrawMeshInstancedIndirect(instanceMesh, subMeshIndex, instanceMaterial, new Bounds(Vector3.zero, new Vector3(100.0f, 100.0f, 100.0f)), argsBuffer); } void OnGUI() { GUI.Label(new Rect(265, 25, 200, 30), "Instance Count: " + instanceCount.ToString()); instanceCount = (int)GUI.HorizontalSlider(new Rect(25, 20, 200, 30), (float)instanceCount, 1.0f, 5000000.0f); } void UpdateBuffers() { // Ensure submesh index is in range if (instanceMesh != null) subMeshIndex = Mathf.Clamp(subMeshIndex, 0, instanceMesh.subMeshCount - 1); // Positions if (positionBuffer != null) positionBuffer.Release(); positionBuffer = new ComputeBuffer(instanceCount, 16); Vector4[] positions = new Vector4[instanceCount]; for (int i = 0; i < instanceCount; i++) { float angle = Random.Range(0.0f, Mathf.PI * 2.0f); float distance = Random.Range(20.0f, 100.0f); float height = Random.Range(-2.0f, 2.0f); float size = Random.Range(0.05f, 0.25f); positions[i] = new Vector4(Mathf.Sin(angle) * distance, height, Mathf.Cos(angle) * distance, size); } positionBuffer.SetData(positions); instanceMaterial.SetBuffer("positionBuffer", positionBuffer); // Indirect args if (instanceMesh != null) { args[0] = (uint)instanceMesh.GetIndexCount(subMeshIndex); args[1] = (uint)instanceCount; args[2] = (uint)instanceMesh.GetIndexStart(subMeshIndex); args[3] = (uint)instanceMesh.GetBaseVertex(subMeshIndex); } else { args[0] = args[1] = args[2] = args[3] = 0; } argsBuffer.SetData(args); cachedInstanceCount = instanceCount; cachedSubMeshIndex = subMeshIndex; } void OnDisable() { if (positionBuffer != null) positionBuffer.Release(); positionBuffer = null; if (argsBuffer != null) argsBuffer.Release(); argsBuffer = null; }}
The following Universal Render Pipeline (URP) shader works with the previous example script:
Shader "Instanced/InstancedShader"{ Properties { _BaseMap ("Albedo (RGB)", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" } Pass { Tags { "LightMode"="UniversalForwardOnly" } HLSLPROGRAM #pragma vertex vert #pragma fragment frag #pragma target 4.5 #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" TEXTURE2D(_BaseMap); SAMPLER(sampler_BaseMap); // The position (xyz) and scale (w) of each instance, set by the example script. StructuredBuffer<float4> positionBuffer; struct Attributes { float4 positionOS : POSITION; float3 normalOS : NORMAL; float2 uv : TEXCOORD0; float4 color : COLOR; }; struct Varyings { float4 positionCS : SV_POSITION; float2 uv : TEXCOORD0; float3 ambient : TEXCOORD1; float3 diffuse : TEXCOORD2; float3 color : TEXCOORD3; float3 positionWS : TEXCOORD4; }; // Rotates a 2D vector by r radians. void rotate2D(inout float2 v, float r) { float s, c; sincos(r, s, c); v = float2(v.x * c - v.y * s, v.x * s + v.y * c); } Varyings vert(Attributes v, uint instanceID : SV_InstanceID) { // Get the data for this instance. float4 data = positionBuffer[instanceID]; // Rotate the instance around the origin over time. Larger instances rotate faster. float rotation = data.w * data.w * _Time.x * 0.5f; rotate2D(data.xz, rotation); // Scale the vertex, then move it to the position of the instance. float3 localPosition = v.positionOS.xyz * data.w; float3 worldPosition = data.xyz + localPosition; float3 worldNormal = v.normalOS; // Calculate simple diffuse lighting from the main light, and ambient lighting from light probes. Light mainLight = GetMainLight(); float ndotl = saturate(dot(worldNormal, mainLight.direction)); Varyings o; o.positionCS = TransformWorldToHClip(worldPosition); o.uv = v.uv; o.ambient = SampleSH(worldNormal); o.diffuse = ndotl * mainLight.color; o.color = v.color.rgb; o.positionWS = worldPosition; return o; } half4 frag(Varyings i) : SV_Target { // Apply the shadows of the main light to the diffuse lighting only. float shadow = MainLightRealtimeShadow(TransformWorldToShadowCoord(i.positionWS)); half4 albedo = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, i.uv); float3 lighting = i.diffuse * shadow + i.ambient; return half4(albedo.rgb * i.color * lighting, albedo.a); } ENDHLSL } }}