Search Unity

MaterialPropertyBlocks and SpriteRenderer

Discussion in '2D' started by HypercubeCore, Oct 9, 2019.

  1. HypercubeCore

    HypercubeCore

    Joined:
    Jul 10, 2018
    Posts:
    2
    I have a Replacement Shader i use on an extra camera for an edge detection effect in my game.
    I also have a script that sets a property in the MaterialPropertyBlock of the object's renderer for this Replacement Shader to use. This works with every renderer, including sprite renderer, but only if the sprite is single and not multiple. If the sprite is part of a multiple sprite, just setting the property block, even with no changes, messes up the texture, sometimes grabbing part of a different texture entirely.

    My code is something like this:
    Code (CSharp):
    1. renderer.GetPropertyBlock(block, 0);
    2. block.SetFloat(propertyName, value); //Removing this line doesn't fix the problem
    3. renderer.SetPropertyBlock(block, 0);
    ¿Is this normal behaviour or is it a bug?

    I know SpriteRenderer uses MaterialPropertyBlocks to set up texture, tiling and color internally, and this issue seems to be related to that. I probably would be able to fix it if i knew the exact internal code SpriteRenderer uses for this.
     
  2. HypercubeCore

    HypercubeCore

    Joined:
    Jul 10, 2018
    Posts:
    2
    Solved! If someone is having trouble with this, what i did was to set up the texture in the material as the texture in the sprite renderer manually, like this:


    Code (CSharp):
    1.  
    2. Texture2D tex = renderer.sprite.texture;
    3. renderer.GetPropertyBlock(block, 0);
    4. block.SetTexture(propertyName, tex);
    5. renderer.SetPropertyBlock(block, 0);
    PropertyName is set as _MainTex in the inspector.
    The thing is, i still don't quite know why this happens because i don't know how SpriteRenderer handles the texture internally, so it's probably not the optimal solution, so if somebody knows something better i would appreciate the help