参考链接:
https://happyfire.blog.csdn.net/article/details/124861373?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-124861373-blog-124758706.235%5Ev38%5Epc_relevant_sort_base2&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-1-124861373-blog-124758706.235%5Ev38%5Epc_relevant_sort_base2&utm_relevant_index=1
GPU instancing的官方介绍:
https://docs.unity3d.com/cn/current/Manual/GPUInstancing.html
GPU instancing可以批量绘制大量相同mesh相同材质的物体,是一种减少drawcall的手段,支持阴影和多光源,比较适合用于绘制草、树
与动态和静态合批不同的是,GPU instancing并不通过合并网格来减少drawcall,而是提交一个网格让gpu绘制很多遍,可以对实例化后的网格进行坐标、旋转、缩放的操作
开启条件:
1.shader要支持GPU instancing,具体见:
https://docs.unity3d.com/cn/current/Manual/gpu-instancing-shader.html
例如:
1 Shader "Custom/SimplestInstancedShader" 2 { 3 Properties 4 { 5 _Color("Color", Color) = (1, 1, 1, 1) 6 } 7 8 SubShader 9 { 10 Tags { "RenderType" = "Opaque" } 11 LOD 100 12 13 Pass 14 { 15 CGPROGRAM 16 #pragma vertex vert 17 #pragma fragment frag 18 #pragma multi_compile_instancing 19 #include "UnityCG.cginc" 20 21 struct appdata 22 { 23 float4 vertex : POSITION; 24 UNITY_VERTEX_INPUT_INSTANCE_ID 25 }; 26 27 struct v2f 28 { 29 float4 vertex : SV_POSITION; 30 UNITY_VERTEX_INPUT_INSTANCE_ID // use this to access instanced properties in the fragment shader. 31 }; 32 33 UNITY_INSTANCING_BUFFER_START(Props) 34 UNITY_DEFINE_INSTANCED_PROP(float4, _Color) 35 UNITY_INSTANCING_BUFFER_END(Props) 36 37 v2f vert(appdata v) 38 { 39 v2f o; 40 41 UNITY_SETUP_INSTANCE_ID(v); 42 UNITY_TRANSFER_INSTANCE_ID(v, o); 43 o.vertex = UnityObjectToClipPos(v.vertex); 44 return o; 45 } 46 47 fixed4 frag(v2f i) : SV_Target 48 { 49 UNITY_SETUP_INSTANCE_ID(i); 50 return UNITY_ACCESS_INSTANCED_PROP(Props, _Color); 51 } 52 ENDCG 53 } 54 } 55 }
2.材质要勾选Enable GPU Instancing
注意点:
1.SRP Batch的优先级高于GPU Instancing,可以使用MaterialPropertyBlock打破SRP Batch
2.GPU Instancing不支持SkinnedMeshRenderer