Damian
Damian

Reputation: 5561

Modify a material at runtime

I want to modify a material's parameter at runtime. The parameter is called "Radio 1" and is defined in a custom shader. I need the change I make to the material to affect all objects that are using it, and that's not working. How can I do so?

I've tried getting one of the objects that use the material and modify the sharedMaterial, and also tried loading the material and modifying it like this:

var mater = Resources.Load("BGRingMat") as Material;
mater.SetFloat("Radio2", bgRingMaterialRadio2);

I see no effects at all. How can I achieve this?

Upvotes: 0

Views: 7772

Answers (2)

Jerdak
Jerdak

Reputation: 4056

Globally modify the shader value for all instances of this material:

Material mat = Resources.Load("BGRingMat") as Material;
mat.SetFloat( "Radio2", bgRingMaterialRadio2);

Or modify for 1 object:

renderer.material = Resources.Load("BGRingMat") as Material;
renderer.material.SetFloat( "Radio2", bgRingMaterialRadio2);

Note that IF you modify an object's material directly first, and then try to use the shared material, nothing will happen:

Material mat = Resources.Load("BGRingMat") as Material;

// Sets Radio2 to bgRingMaterialRadio2
renderer.material.SetFloat( "Radio2", bgRingMaterialRadio2);

// Doesn't do anything to the current object as this object now has its own copy.
mat.SetFloat( "Radio2", 0.0f);

Upvotes: 0

sune
sune

Reputation: 171

I just tested your case. It should be able to work as you desire it to. If you don't get any nullrefs, the only error I can imagine is that "Radio2" is a wrong variable name. If you try to modify a variable using a wrong name, you will not get any errors. In your text you mention the variable as "Radio 1".

Upvotes: 1

Related Questions