ComputeShader绘制全屏纯色纹理

参考

Getting Started With Compute Shaders In Unity

环境

Win10
Unity20194.40

全屏纯色纹理示例

使用ComputerShader逐个像素设置颜色

  1. ComputeShader脚本
    设置纹理颜色
#pragma kernel CSMain

RWTexture2D<float4> Result;//纹理
half4 solidColor;//颜色

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
      Result[id.xy] = solidColor;//设置颜色 id.xy对应屏幕上的像素点
}
  1. UseSolidComputeShader脚本
    调用ComputeShader,绘制纯色纹理
using UnityEngine;
public class UseSolidComputeShader : MonoBehaviour
{
    [SerializeField] ComputeShader computeShader;
    RenderTexture renderTexture;
    int functionId;
    int groupsX;
    int groupsY;

    public RenderTexture Texture => renderTexture;

    public void Init(int width, int height)
    {
        renderTexture = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
        renderTexture.enableRandomWrite = true;
        renderTexture.Create();

        functionId = computeShader.FindKernel("CSMain");
        groupsX = Mathf.CeilToInt(renderTexture.width / 8f);//向上取整,避免小于纹理的宽度
        groupsY = Mathf.CeilToInt(renderTexture.height / 8f);
        computeShader.SetTexture(functionId, "Result", renderTexture);
    }

    public void Draw(Color color)
    {
        computeShader.SetVector("solidColor", color);
        computeShader.Dispatch(functionId, groupsX, groupsY, 1);
    }
}
  1. TestSolidColor脚本
    按下D键,绘制纯色纹理,显示在Rawimage上
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.UI;
public class TestSolidColor : MonoBehaviour
{
    [SerializeField] UseSolidComputeShader useSolidComputeShader;

    [SerializeField] RawImage rawImage;

    private void Awake()
    {
        useSolidComputeShader.Init(Screen.width, Screen.height);
        rawImage.texture = useSolidComputeShader.Texture;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.D))
        {
            Profiler.BeginSample("Random Solid Color");
            useSolidComputeShader.Draw(Random.ColorHSV());
            Profiler.EndSample();
        }
    }
}
  1. 场景层级
    在这里插入图片描述
    Draw对象,添加TestSolidColor脚本,UseSolidComputeShader,设置引用。
    RawImage为全屏大小
  2. 运行,效果图如下
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值