Unity 2022
I got codes like BELOW, and then set the output to _MainTex, always shows BLACK Texture.
When a change RWTexture2D to RWTexture2D, it works fine to show RED Texture
RWTexture2D resultTexture;
[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
resultTexture[id.xy] = 255;
}
kernelIndex = computeShader.FindKernel(“CSMain”);
descriptor = new RenderTextureDescriptor(1024, 1024, RenderTextureFormat.RInt, 0);
outputTexture = new RenderTexture(descriptor);
outputTexture.enableRandomWrite = true;
computeShader.SetTexture(kernelIndex, “resultTexture”, outputTexture);
computeShader.Dispatch(kernelIndex, descriptor.width / 8, descriptor.height / 8, 1);
By default, the _MainTex
in a regular shader, defined as sampler2D _MainTex;
is going to be a float4
texture definition. You would instead need to use a shader with it defined as Texture2D<uint> _MainTex;
and then sample like uint num = _MainTex.Load(float3(i.uv, 0)).r;
Part 2:
My answer above does work, but it still messes up the upper 2 bits due to float4 frag().
So, here is the solution to that, using compute shaders:
So, we need to find a way to fill the unsigned-integer-texture with uint4
Unity doesn't seem to allow returning uint4 from frag() in shader. It compiles but returns zeros.
Therefore, we can do it via compute shader. Create one and put this code:
// ComputeShaderExample.compute
#pragma kernel CSMain
// Declare the RWTexture with uint4 …
1 Like