Lerping in a shader

I’m trying to create a basic shader that just lerps between two base colors. The lerping works if I adjust the blend knob, but now I want to make it so it flashes by it’s self.

I was able to find examples that used a shader along side a script that passes the blend value, but I want to do it all in the shader.

I though I programmed it correctly, but it doesn’t appear to be fading between the two colors.

My shader:

Shader "Game/Solid/SolidFlash"
{
	Properties
	{
		_Blend("Blend", Range(0, 1)) = 0.5
		_BlendSpeed("Blend Speed", Range(0, 50)) = 0.5
		_Color("Main Color", Color) = (1, 1, 1, 1)
		_Color2("Flash Color", Color) = (1, 1, 1, 1)
		_MainTex("Texture 1", 2D) = "white" {}
	}
		SubShader
	{
		Tags{ "Queue" = "Transparent" "RenderType" = "Transparent" }
		LOD 300
		Pass
	{
		SetTexture[_MainTex]

	}

		CGPROGRAM
	#pragma surface surf Lambert

	sampler2D _MainTex;

	fixed4 _Color;
	fixed4 _Color2;
	float _Blend;
	float _BlendSpeed;

	int forward = 1;

	struct Input
	{
		float2 uv_MainTex;
		float2 uv_Texture2;
	};

	void surf(Input IN, inout SurfaceOutput o)
	{

		if (forward == 1) {
			_Blend += unity_DeltaTime.x / _BlendSpeed;
			if (_Blend >= 1)
				forward = 0;
		}
		else {
			_Blend -= unity_DeltaTime.x / _BlendSpeed;
			if (_Blend <= 0)
				forward = 1;
		}

		fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
		o.Albedo = (lerp(_Color, _Color2, _Blend)+ tex * tex.a); // lerp(t1, t2, _Blend);
	}
	ENDCG
	}
		FallBack "Diffuse"
}

While valid syntax, using if statements in a shader is considered a big no-no that should be absolutely avoided if possible. The GPU is a pipeline processor that can run a fixed set of instructions against a massive number of fragments very efficiently. But as soon as you implement branching logic, that pipeline must be rebuilt - defeating the parallelism at which GPUs excel.

A better solution would be to perform calculations in a C# script on the CPU and just pass that value to the shader, as in the examples you said you’ve already found.

Something like this @lancer ?

void surf(Input IN, inout SurfaceOutput o)
	{
		_Blend = (1+_SinTime.w) / 2;

		fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
		o.Albedo = lerp(_Color, _Color2, _Blend) * tex;
	}