Search Unity

SpriteRenderer.SetPropertyBlock has no effect

Discussion in 'Scripting' started by StrongGuy, Jul 28, 2017.

  1. StrongGuy

    StrongGuy

    Joined:
    Aug 12, 2014
    Posts:
    13
    Hi, I am using Unity 5.5.1

    I have a custom shader, it's created from Sprite/Default, and I added 2 properties, like this
    Code (csharp):
    1.  
    2.     Properties
    3.     {
    4.         [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
    5.         _Color ("Tint", Color) = (1,1,1,1)
    6.         [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    7.         [PerRendererData] _ActorY ("ActorY", Float) = 0             // My own data
    8.         [PerRendererData] _ActorZ ("ActorZ", Float) = 0             // My own data
    9.     }
    10.  
    And I set these 2 properties in my script:

    Code (csharp):
    1.  
    2. SpriteRenderer SR;
    3. MaterialPropertyBlock matProBlock = null;
    4. void Update()
    5. {
    6.         if (matProBlock == null)
    7.             matProBlock = new MaterialPropertyBlock();
    8.  
    9.         SR.GetPropertyBlock(matProBlock);
    10.         matProBlock.SetFloat("_ActorY", trans.position.y);
    11.         matProBlock.SetFloat("_ActorZ", m_zHeight);
    12.         SR.SetPropertyBlock(matProBlock);
    13. }
    14.  
    The problem is:
    _ActorY and _ActorZ are always 0 when I get them in shader.

    If I just use this code, everything is fine.
    Code (csharp):
    1.  
    2. void Update()
    3. {
    4.     SR.material.SetFloat("_ActorY", trans.position.y);
    5.     SR.material.SetFloat("_ActorZ", m_zHeight);
    6. }
    7.  
    So, does SpriteRender eat my properties?
     
  2. StrongGuy

    StrongGuy

    Joined:
    Aug 12, 2014
    Posts:
    13
    I already know why, I didn't call SetPropertyBlock
    Code (csharp):
    1.  
    2. SR.SetPropertyBlock(matProBlock);
    3.  
    But I also figure out that if SetPropertyBlock is called for every sprite, then these sprites will not be batched together.
    The way to use MaterialPropertyBlock and also enable batching is:
    Pass _ActorY and _ActorZ through _Color, or vertex, or UV2, UV3..etc.