Is it possible to create a transparent material that is only transparent to a certain other material or objects on a layer?

For example MaterialX is opaque to all materials except to MaterialY or layers on Y


1 Answer 1


We can do something similar to this with the stencil buffer.

Arrange your draw order so the materials/objects that should show through get drawn after all opaque/alpha tested content except your selectively transparent material. Say, putting them in the "AlphaTest+1" draw queue. This ensures anything that will occlude them has already been drawn and is in the depth buffer, so we'll skip drawing to those occluded pixels.

This material should write a guard value to the stencil buffer wherever it successfully draws to the screen. This can be any number 1-255 you're not using for another stencil effect in your scene.

Now, your selectively transparent material should render after these objects (say, in queue "AlphaTest+2"). It also gets a stencil block in its shader, but one that reads the stencil buffer, and draws only if it's not equal to the guard value you chose.

In this way, the materials that wrote the guard value to the stencil buffer "punch through" or "mask out" this later material from drawing over them, while still respecting the usual depth ordering otherwise, and without needing to draw them twice or to an off-screen render target that needs to be composited in.

This only achieves alpha test style transparency, not a soft translucent blend, so you'll get a harsh and potentially stairstep-aliased edge where these objects overlap, unless you're using an anti-aliasing post-process effect.

Other translucent effects should layer correctly with it, but you will notice one funny effect if there's translucent content like smoke particles between the selectively transparent object in front and one of the things that's allowed to show through it in the back: the window we cut in the front object will let both the back object and all the intervening smoke through, rather than showing only the back object unobscured by smoke.

Because you haven't told us how this is used in your game or what other material/particle effects it needs to interact with, I don't know whether these artifacts are as desired, moot, or a problem for your application. There are workarounds, if either is a deal-breaker — just edit your question to describe and show more context/application.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .