How can I apply an outline effect in Unity?

How can I apply an outline effect in Unity?

I want to apply an outline effect for several objects on the scene. Nope, the standard outline shader from the toon-shader package don't met my criteria.
I want to create an effect like this: 

To implement this effect I want to:
1) Render all my selected objects into a texture, taking the depth into attention. So if my selected object is occluded by another objects it must be displayed in my render texture, like this:

2) Render the scene.
3) Blur my render texture and then copy all non-null (null is empty scene) and non-one (1 is the object itself) to the screen to make it look like this: 

So, I have the question: How can I render the separate objects to the texture, taking care about occluders (depth)? Yep, I know about Graphics.SetRenderTarget Graphics.DrawMeshNow, but I also need to take care about the depth, because without it, it will look like this:

Please help, I feel stuck.

Solutions/Answers:

Answer 1:

The Unity team published a nice slide deck at SIGGRAPH 2011 with a whole palette of special effects that can be achieved with depth. These are low-cost when using deferred rendering, but still available when using forward rendering at the cost of a pass to create the depth texture.

Their outline effect is described on slides 46-47, and should be possible to adapt to your needs.

Instead of the Sobel Filter on depth as they suggest, just read the depth buffer at the current fragment position. If it agrees with the depth of the fragment you’re rendering (within a rounding tolerance), it’s your object, so output 1. If it’s substantially closer, it’s an occluder, so output 0. (You can also choose to output 1 only for fragments adjacent to the edges, leaving the interior 0 if you prefer)

After that, you can continue with the approach you’ve described above.

References