使用ComputeShader把图片变成灰度图并替换到场景内物体上

// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel Gray

Texture2D inputTexture;
// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
RWTexture2D<float4> Result;



[numthreads(8,8,1)]
void Gray (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);
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        RenderTexture rt = new RenderTexture(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);
    }

    public Texture2D tex;
    private ComputeShader c;

    // Update is called once per frame
    void Update()
    {
        
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值