Use grabpass to determine color of pixel before rendering the current pixel.

I have been reading up on grabpass and shader programming. I am relatively new, but understand concepts and syntax (or can look up references).

I am curious how to grab the pixel color that is being rendered prior to rendering the current pixel. I know I need a grabpass (and use the one where I pass in a material name) and then determine my pixel coordinate, and then check this coordinate in the grabbed material to get the color I want.

I currently want to use cg as my main language (most applicable) and shaderlab for just the grabpass and maybe color retrieval if necessary.

My overall goal is to use the color of the pixel to change a font color to black or white, as to make it easily readable, while a status bar grows from left to right behind it.
I currently have a shader that I have applied to a plane, and I have a unity changeable input color, and my shader turns black and white depending on the color.
I also added grabpass and specified a material name. In my cg-shader section I specified the material name as a sampler2D type.

How do I achieve this effect?

Here’s a simple shader that blends the object via GrabTexture instead of regular alpha blending:

Shader "Custom/GrabShaderTextured" {

	Properties {
		_MainTex ("Base (RGB)", 2D) = "white" {}
	}
    SubShader {
        // Draw ourselves after all opaque geometry
        Tags { "Queue" = "Transparent" }

        // Grab the screen behind the object into _GrabTexture
        GrabPass { }
        
		CGPROGRAM
		#pragma surface surf Lambert vertex:vert
		#pragma debug

		sampler2D _MainTex;
		sampler2D _GrabTexture;

		struct Input {
			float2 uv_MainTex;
			float4 grabUV;
		};

		void vert (inout appdata_full v, out Input o) {
			//set custom value
        	float4 hpos = mul (UNITY_MATRIX_MVP, v.vertex);
        	o.grabUV = ComputeGrabScreenPos(hpos);
      	}


		void surf (Input IN, inout SurfaceOutput o) {
			half4 c = tex2D (_MainTex, IN.uv_MainTex);
			half4 p = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(IN.grabUV));
			o.Albedo = c.rgb * p.rgb; 
		}
		ENDCG
	
	} 

}

However you might get your result much cheaper by using some advanced blending logic…

You can try Blend OneMinusDstColor Zero to use hardware to invert. Your source colour should be white.

Can I avoid using a surface shader, or make the surface shader omit light? I want to use a fragment shader for efficiency on mobile.

If you want efficiency you should try to use regular blending like Daniel suggested. GrabTexture will have an impact on performance.

The vertex fragment part would look pretty similar in a CG (non-surface) shader.