- Home /
set material property only for one object?
Hi,
I made myself a little progress bar shader. I just have a UI Image with that shader and the "_Progress" property affects the length of the bar.
It works fine, but my problem is that when I have two progress bars, both of them will show the same progress since something like
healthBar.material.SetFloat("_Progress",player.health/player.maxHealth);
will cause a change on the material which is used by both objects.
How can I change that material property only for one of the bars?
Answer by Baste · May 29, 2015 at 03:17 PM
On startup, create a clone of the material, and use that instead:
void Awake() {
healthBar.material = new Material(healthBar.material);
}
That Material constructor copies all of the properties of the old material, but it's a different instance, so your old code will now change only that material.
Thanks, that's a good solution.
just one question:
Will both materials still use the same shader then?
Otherwise, i'll introduce unnecessary shader switches
Yes. When you copy the material, you get all the properties of the old one, yes. This includes the shader, and all of the settings on the shader - like the texture and additional colors and whatever.