Hi! I use script for changing a prefab’s shader’s colors so that I just have to duplicate many times and still have different colors of same object. Then I found out a problem is when I change the color from Inspector, the object does not update unless I press play. Beside not convenience and also cause a problem for baking light mapping. How to update the color as I change them?
My guess is, what you’re trying to do won’t work. And if you force it to work, Unity will complain about memory leaks.
Materials are global. Multiple renderers can all be assigned the same material. If you modify the material, all of the renderers will show the change.
However, when you modify a shader value on a renderer’s material at runtime, what you’re actually doing is making a copy of that material, and assigning it to the object. You can confirm this by looking at the Renderer while playing. The material name probably has “(Instance)” on the end of it at runtime. That means Unity has duplicated the material so that you can override the shader values just for that one renderer, without affecting all other renderers that use that material. Those “Instance” materials are temporary allocations which take up memory at runtime, but which will disappear when you exit play mode.
So, if you have a script that’s changing shader values on a per-object basis, it necessarily involves creating temporary instances of the material. If you do that when not in play mode, Unity will complain that you’re creating memory leaks.
So, what you’re trying to do isn’t really something Unity wants you to do. If you want multiple similar materials that look different, I’d recommend you just creating many materials and assign them to each prefab. Having a lot of different materials isn’t really a performance problem if they’re all using the same shader. Unity tends to batch that stuff up anyway.
is good to know many materials won’t cause a lot in game. I thought use script change their color can save memories.
So I guess should reproduce some works, lucky not too much effort. hahaha!