I have a shader on a gameObject, Lets call it FooShader. In FooShader there is a public property called _fooVal I want to update in real time.
I’ve created a blank C# script on the same gameObject.
My first problem is how do I reference this FooShader script? And then once I have a correct reference change my _fooVal property?
Since shaders are attached to materials, you need a reference to the material that’s being used.
The properties can be set through methods on a material instance, for example the following:
public class FooScript : MonoBehaviour
{
public Material material;
void Update()
{
this.material.SetFloat("_FooVal", Time.time);
}
}
All objects sharing this material will have the same value in the above example. If you need independent values for an indeterminate amount of objects, you can do the following:
public class FooScript : MonoBehaviour
{
public Material material;
private Material materialInstance;
void Awake()
{
this.materialInstance = (Material)Instantiate(this.material);
}
void Update()
{
this.materialInstance.SetFloat("_FooVal", Time.time);
}
}
You can find the rest of the SetX methods in the documentation. By now, you’ve probably found the solution but I’ll post this anyways.