- Home /
SetReplacementShader to affect only certain objects
Camera.SetReplacementShader seems to allow to render all objects whose original material contains a certain tag using a replacement shader. All objects whose original shader does not contain the specified tag do not get rendered at all.
I would like to render all objects that do not contain this specified tag using their original shader while those that do contain the tag get rendered using the replacement shader. (so, instead of not rendering objects that don't contain the tag, they shall be rendered normally)
How can I achieve this?
Answer by psantoki · Apr 11, 2014 at 11:38 PM
Of all the features in Unity that do not work, SetReplacementShader does not work with absolute precision. 100% fail rate. Don't use this function.
I owe you a more productive answer.
There are a lot of ways to replace materials, during runtime, offline while building streamable assets, in the editor when not running. I'll assume you want runtime replacement of custom materials.
The best way to replace shaders at runtime is to gather all materials that need replacement and manually set your own shader. You can do this by walking through the scene or enumerating all shaders. This is the easiest method and offers the most control, you know exactly what you're replacing and what you're getting.
This doesn't work for terrain and grass, which do not expose their materials to you. (With terrain you can pick a substitute material in the inspector, for grass you must download the Unity grass shaders and add them to your project. This part isn't perfectly clear to me and it's certainly not documented, but you can edit these shaders or create your own with the same internal names ["Hidden/TerrainEngine/Details/WavingDoublePass"] and Unity will secretly, quietly, magically replace the stock grass shader with this one)
The problem with SetReplacementShader is that it cannot just replace one shader, to the confusion of everyone. It's an awful function that wipes out everything in the scene but the shader you want to replace. This is madness. (From the documentation: "any tag types not found in the replacement shader will be not rendered")
Answer by cmz-neu4590 · Jul 24, 2018 at 05:51 PM
I know this is an old post but for whomever stumbles upon this i would like to try to give another more easy solution than playing with resetting materials through the whole scene and tedious stuff like that. This is not a perfect solution and i have not fully tested it and i will not explain it fully because i'm in a hurry but at least it may give someone and idea on how to do it... Use 2 cameras, set replacement shader in the second one, have cam1's culling mask render everything except one layer and cam2 one render that layer(set the layer of the objects that you want the replacement shader to apply to, to it ), have cam2's clear flag to "depth only" and it depth higher than cam1. This seemed to work for me, hope it helps someone.