参考
Getting Started With Compute Shaders In Unity
环境
Win10
Unity20194.40
全屏纯色纹理示例
使用ComputerShader逐个像素设置颜色
- 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对应屏幕上的像素点
}
- 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);
}
}
- 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();
}
}
}
- 场景层级
Draw对象,添加TestSolidColor脚本,UseSolidComputeShader,设置引用。
RawImage为全屏大小 - 运行,效果图如下