- Home /
Is it possible to modify a material/shader in code?
Hello, Im creating a simple Vr project where i am attempting to mix two "chemicals". I followed a nice video on a pouring effect by VR with ANdrew. He uses a panning diffuse shader to create a very nice stream. I am attempting to modify this stream if I pour a red chemical into a blue chemical i want the blue chemical to turn to pink and its stream to reflect that. I can change the vials contents etc however i cannot seem to change the stream as i cant seem to effect the material and or shader thats drawing it. Here is the shader:
   Properties
    {
         _MainTex ("Sprite Texture", 2D) = "white" {}
         _Color ("Tint", Color) = (1,1,1,1)
         _Speed("Speed", float) = 0.0
         [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
         [HideInInspector] _RendererColor ("RendererColor", Color) = (1,1,1,1)
         [HideInInspector] _Flip ("Flip", Vector) = (1,1,1,1)
         [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {}
         [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0
     }
Here is one of my attempts to force change the stream
     private void Awake()
     {
         //chemicalColor = GetComponent<Material>().color;
 
         lineRenderer = GetComponent<LineRenderer>();
         Material mat = lineRenderer.material;
         
         mat.color = Color.green;
         //float alpha = 1.0f;
         //Gradient gradient = new Gradient();
         //gradient.SetKeys(
         //    new GradientColorKey[] { new GradientColorKey(Color.green, 0.0f), new GradientColorKey(Color.red, 1.0f) },
         //    new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
         //);
         //lineRenderer.colorGradient = gradient;
         print("Hello");
         splashParticle = GetComponentInChildren<ParticleSystem>();
     }
Answer by jackmw94 · Nov 13, 2020 at 07:29 PM
To change a variable inside a shader you need to use the Set_ functions on the material. 
 So to change the tint to green you'd use: mat.SetColor("_Color", Color.green); 
 Setting this via string can however be a little expensive so you can improve this by caching the nameId: private static readonly int ColorShaderId = Shader.PropertyToID("_Color");
Did you have any success with this? If not then let me know but if so please accept my answer! :)
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                