Search Unity

Help Wanted Dynamic batchting influence the shader in game view

Discussion in 'Shaders' started by CHOPJZL, Apr 4, 2021.

  1. CHOPJZL

    CHOPJZL

    Joined:
    Dec 5, 2016
    Posts:
    54
    Hello all,
    I write a shader to scale the size of the model
    Code (CSharp):
    1.  CGPROGRAM
    2.         #pragma surface surf Standard fullforwardshadows vertex:vert addshadow
    3.  
    4.         #pragma target 3.0
    5.  
    6.         sampler2D _MainTex;
    7.  
    8.         struct Input
    9.         {
    10.             float2 uv_MainTex;
    11.         };
    12.  
    13.         half _Glossiness;
    14.         half _Metallic;
    15.         fixed4 _Color;
    16.        
    17.         float _scaleX;
    18.         float _scaleY;
    19.         float _scaleZ;
    20.  
    21.         UNITY_INSTANCING_BUFFER_START(Props)
    22.             // put more per-instance properties here
    23.         UNITY_INSTANCING_BUFFER_END(Props)
    24.        
    25.         void vert(inout appdata_full data){
    26.             float4 modifiedPos = data.vertex;
    27.                  
    28.             modifiedPos.x *= _scaleX;
    29.             modifiedPos.y *= _scaleY;
    30.             modifiedPos.z *= _scaleZ;
    31.                                      
    32.             data.vertex = modifiedPos;
    33.         }
    34.  
    35.         void surf (Input IN, inout SurfaceOutputStandard o)
    36.         {
    37.             // Albedo comes from a texture tinted by color
    38.             fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
    39.             o.Albedo = c.rgb;
    40.             // Metallic and smoothness come from slider variables
    41.             o.Metallic = _Metallic;
    42.             o.Smoothness = _Glossiness;
    43.             o.Alpha = c.a;
    44.         }
    45.         ENDCG
    The shader looks different in Scene and Game
    3box vertex.jpg

    After I turn off Dynamic Batching in Project Settings, the shader become the same in Scene and Game.

    But why is this? Is it a bug? I am using 2020.3.0f1c1
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    11,032
    Working as expected.

    Static & dynamic batching merges multiple meshes into one mesh that's been pre-transformed into world space. That means the mesh that's being rendered has its pivot at the world origin and the pivot and scale information of the original game objects is no longer known by the shader. So when you scale a batched mesh it's the equivalent of scaling a parent game object at the world origin vs. scaling each object individually.

    If you need to scale objects individually from their original pivot, scale them with a script, or disable batching for the project, or disable batching for that shader.
    Tags { "DisableBatching" = "True" }
     
    CHOPJZL likes this.
unityunity