Search Unity

Question Lock On UI to render in front of everything EXCEPT the player.

Discussion in 'Shaders' started by Renatusdev, Feb 19, 2021.

  1. Renatusdev

    Renatusdev

    Joined:
    Dec 9, 2018
    Posts:
    35
    I've been working on a Lock On System and I'm just about done. The problem I'm facing is with the UI. I want to render that sprite in front of everything except the player. I made a shader with ZTest set to Always, this way it renders in front of everything. Great! But then it backfired by rendering in front of the player.


    I tried render queues, but didn't get it to work. I'm extremely bad at shader stuff but I'm trying here. Any help would be more than welcome.
    upload_2021-2-19_12-16-24.png
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    There are a couple of ways to fix this, but most of them involve some amount of custom shader work.

    The one option that does not require custom shaders is to play with the render queues, as you already figured out. The trick to get it to work is the player's material needs it's queue to be higher than the lock on diamond's material, which in turn needs to be higher than than anything else in the scene. You also want the shader used on the lock on diamond to not have
    ZWrite On
    , though this can have the side effect of not showing over the skybox unless the queue is >2500, which puts it into the transparency queue range. But then your player's material needs to also be in the transparency queue range which will cause issues for any post processing you might want to do.

    Another alternative would be to use stencils. This is fairly straight forward to do with the built in rendering pipeline, but a little more convoluted when using the URP. You'd need to create some basically "invisible" shaders that you'll use to write to the stencil buffer by re-render the player model. Then render the lock on diamond afterward with a shader that won't draw anywhere the stencil buffer has been written to.

    This tutorial should help.
    https://theslidefactory.com/see-through-objects-with-stencil-buffers-using-unity-urp/
     
    Renatusdev likes this.