using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
publicclass PostEffectsBase : MonoBehaviour {
protectedvoidStart() {
CheckResources();
}
// Called when startprotectedvoidCheckResources() {
bool isSupported = CheckSupport();
if (isSupported == false) {
NotSupported();
}
}
// Called in CheckResources to check support on this platformprotectedboolCheckSupport() {
if (SystemInfo.supportsImageEffects == false || SystemInfo.supportsRenderTextures == false) {
Debug.LogWarning("This platform does not support image effects or render textures.");
returnfalse;
}
returntrue;
}
// Called when the platform doesn't support this effectprotectedvoidNotSupported() {
enabled = false;
}
// Called when need to create the material used by this effectprotected Material CheckShaderAndCreateMaterial(Shader shader, Material material) {
if (shader == null) {
returnnull;
}
if (shader.isSupported && material && material.shader == shader)
return material;
if (!shader.isSupported) {
returnnull;
}
else {
material = new Material(shader);
material.hideFlags = HideFlags.DontSave;
if (material)
return material;
elsereturnnull;
}
}
}
using UnityEngine;
using System.Collections;
publicclass MotionBlur : PostEffectsBase {
public Shader motionBlurShader;
private Material motionBlurMaterial = null;
public Material material {
get {
motionBlurMaterial = CheckShaderAndCreateMaterial(motionBlurShader, motionBlurMaterial);
return motionBlurMaterial;
}
}
[Range(0.0f, 0.9f)]
publicfloat blurAmount = 0.5f;
private RenderTexture accumulationTexture;
void OnDisable() {
DestroyImmediate(accumulationTexture);
}
void OnRenderImage (RenderTexture src, RenderTexture dest) {
if (material != null) {
if (accumulationTexture == null || accumulationTexture.width != src.width || accumulationTexture.height != src.height) {
DestroyImmediate(accumulationTexture);
accumulationTexture = new RenderTexture(src.width, src.height, 0);
// 不显示到面板上也不会保存
accumulationTexture.hideFlags = HideFlags.HideAndDontSave;
// 当前src
Graphics.Blit(src, accumulationTexture);
}
// 表示需要进行渲染纹理恢复操作// 发生在渲染到渲染纹理而该纹理又没有被提前清空或者销毁的情况下
accumulationTexture.MarkRestoreExpected();
material.SetFloat("_BlurAmount", 1.0f - blurAmount);
Graphics.Blit (src, accumulationTexture, material);
Graphics.Blit (accumulationTexture, dest);
} else {
Graphics.Blit(src, dest);
}
}
}