參考
Getting Started With Compute Shaders In Unity
環境
Win10
Unity20194.40
全屏純色紋理示例
使用ComputerShader逐個像素設置顏色
- ComputeShader腳本
設置紋理顏色
#pragma kernel CSMainRWTexture2D<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為全屏大小 - 運行,效果圖如下