I’m trying to set shader parameters in a material at runtime and I would like them to be applied uniquely per instance of the material. I’m referencing the renderer and it’s material so this should create a material instance when modifying these parameters.
Currently I am successfully able to use Material.SetTexture() to set a different texture per material instance but I am not able to do this with Material.SetFloat(). That will end up setting the float for all objects with that material rather than setting it per instance. How do I get Unity to set the float per instance rather than across all objects using that material?
Here is some of the code I’m using. I edited down the shader code to just show the more relevant parts:
//In C# code
public void SetRiverTexture(bool bFlipX,bool bFlipY,Sprite riverSprite)
{
spriteRenderer.material.SetTexture("_RiverTex",riverSprite.texture);
if(bFlipX)
spriteRenderer.material.SetFloat("_FlipX",1f);
if(bFlipY)
spriteRenderer.material.SetFloat("_FlipY",1f);
}
//In shader
Properties
{
_RiverTex ("River Texture", 2D) = "white" {}
[Toggle] _FlipX ("Flip River X", Float) = 0
[Toggle] _FlipY ("Flip River Y", Float) = 0
}
CGPROGRAM
#pragma multi_compile _FLIPX_OFF _FLIPX_ON
#pragma multi_compile _FLIPY_OFF _FLIPY_ON
sampler2D _RiverTex;
void surf (Input IN, inout SurfaceOutput o)
{
fixed2 uv = IN.uv_MainTex;
#if _FLIPX_ON
uv.x = 1.0 - uv.x;
#endif
#if _FLIPY_ON
uv.y = 1.0 - uv.y;
#endif
fixed4 c = tex2D (_RiverTex, uv);
o.Albedo = c.rgb * c.a;
o.Alpha = c.a;
}
ENDCG