// Each #kernel tells which function to compile; you can have many kernels#pragmakernel Gray
Texture2D inputTexture;// Create a RenderTexture with enableRandomWrite flag and set it// with cs.SetTexture
RWTexture2D<float4> Result;[numthreads(8,8,1)]voidGray(uint3 id : SV_DispatchThreadID){float r = inputTexture[id.xy].r;float g = inputTexture[id.xy].g;float b = inputTexture[id.xy].b;float res = r *0.299+ g *0.587+ b *0.114;
Result[id.xy]=float4(res,res,res,1);}
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEditor;publicclassNewBehaviourScript:MonoBehaviour{// Start is called before the first frame updatevoidStart(){RenderTexture rt =newRenderTexture(tex.width, tex.height,24);
rt.enableRandomWrite =true;
rt.Create();
c = AssetDatabase.LoadAssetAtPath<ComputeShader>("Assets/OverdrawMonitor/Editor/Resources/Gray.compute");int k = c.FindKernel("Gray");
c.SetTexture(k,"inputTexture",tex);
c.SetTexture(k,"Result",rt);
c.Dispatch(k,tex.width/8,tex.height/8,1);GameObject go= GameObject.FindWithTag("sphere");Material mat = go.GetComponent<Renderer>().material;
mat.SetTexture("_MainTex",rt);}publicTexture2D tex;privateComputeShader c;// Update is called once per framevoidUpdate(){}}