shader代码
Shader "
FlickerEffect"
{
Properties
{
_MainTex ("Texture(RGB)", 2D) = "white" {}
_FlickerColor("FlickerColor",Color)=(1,1,1,1)
_LerpLevel("LerpLevel",Range(0.0,1.0))=1.0
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
half4 _FlickerColor;
fixed _LerpLevel;
half4 frag(v2f_img i):SV_Target
{
//如果纹理为null,就单独显示颜色
half4 renderTex=tex2D(_MainTex,i.uv);
//处理颜色,正常图层叠加 结果色=混合色 * 混合色不透明度值 + 基色 * (100% - 混合色不透明度值)。
half r=_FlickerColor.r*_FlickerColor.a+renderTex.r*(1-_FlickerColor.a);
half g=_FlickerColor.g*_FlickerColor.a+renderTex.g*(1-_FlickerColor.a);
half b=_FlickerColor.b*_FlickerColor.a+renderTex.b*(1-_FlickerColor.a);
half a= _FlickerColor.a+(1-_FlickerColor.a)*renderTex.a;
half4 targetColor=half4(r,g,b,a);
//lerp(x,y,s) return x+s(y-x)
half4 finalColor=lerp(renderTex,targetColor,_LerpLevel);
return finalColor;
}
ENDCG
}
}
}
实现屏幕后处理,调用OnRenderImage,使用shader
public Material material
{
get {
if (curMaterial == null)
{
curMaterial = new Material(curShader);
curMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return curMaterial;
}
}
void Start () {
curShader = Shader.Find("ORG/FlickerEffect");
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (curShader != null)
{
material.SetFloat("_LerpLevel", lerpLevel);
if (flickerTexture != null)
material.SetTexture("MainTex", flickerTexture);
material.SetColor("_FlickerColor", flickerColor);
Graphics.Blit(source, destination, material);
}
else
{
Graphics.Blit(source, destination);
}
}
使用协程实现等待执行
IEnumerator ToFlicker()
{
while (true)
{
if (remainDuration < 1)
break;
remainDuration--;
lerpLevel = remainDuration / duration;
lerpLevel = Mathf.Clamp(lerpLevel, 0, 1f);
yield return null;
}
Destroy(this);
}
unity设置打包时包含shader文件
保存时对应的工程文件: