ShaderLab: Shader that renders against objects, but transparent against skybox

I’ve done a lot of reading, and I’ve written a few shaders, but I’m far from an expert. My MO is as follows:

The shader below renders a plain colour object (using an alpha channel) against any object in my scene. What I would like to do is modify the shader so that any part of the object that’s being projected against the skybox (i.e. there is no object behind it) is completely transparent.

Shader "Custom/TransAgainstSkybox" {
    Properties {
        _Color ("Main Color", Color) = (0,0,0,1)
    }
    SubShader {
        Tags {"RenderQueue"="transparent" "RenderType"="transparent" }
        LOD 4000
        ZWrite On
        Cull Off
 
        CGPROGRAM
        #pragma surface surf Lambert alpha
 
        struct Input {
            float3 worldRefl;
            float4 _Color;
        };
        float4 _Color;
        void surf (Input IN, inout SurfaceOutput o) {
            o.Albedo = _Color.rgb;
            o.Alpha = _Color.a;
        }
        ENDCG
    } 
    FallBack "Transparent/Diffuse"
}

The yellow circle in the below diagrams is “on top”, and uses the shader in question. At the moment, the shader renders as follows:

18784-before.gif

But what I actually want it to do is this:

18785-after.gif

It would be handy for the transparent area in the second diagram to be alpha-controlled too, instead of being completely transparent.

Any help appreciated!

  1. Render the transparent mesh with ColorMask A.
  2. Render the skybox with Blend One Zero, Zero OneMinusSrcAlpha.
  3. Render the transparent mesh again,using Blend DstAlpha OneMinusDstAlpha.