How to write to RWTexture3D in Pixel Shader

It seems like writing to a RWTexture2D in a pixel shader is possible; I have succeeded in doing this. But when it comes to writing to a RWTexture3D, it doesn’t seem to work at all.

Shader "Custom/RenderToVolume"
		_MainTex ("Diffuse (RGBA)", 2D) = "white" {}

			Tags { "RenderType"="Opaque" }
			Cull Off ZWrite Off ZTest Always Fog { Mode Off }

			#pragma target 5.0
			#pragma vertex vert
			#pragma fragment frag
			#pragma exclude_renderers flash gles opengl

			#include "UnityCG.cginc"

			sampler2D _MainTex;

			RWTexture3D<float4> volumeTex;
			float volumeResolution;
			float4 volumeParams;

			struct ApplicationToVertex 
				float4 vertex : POSITION;
				float4 texcoord : TEXCOORD0;

			struct VertexToFragment 
				float4 pos : SV_POSITION;
				float4 wPos : TEXCOORD0;
				float2 uv : TEXCOORD1;

			void vert(ApplicationToVertex input, out VertexToFragment output)
				output.pos = mul (UNITY_MATRIX_MVP, input.vertex);
				output.wPos = mul(_Object2World, input.vertex);
				output.uv = input.texcoord.xy;

			void frag(VertexToFragment input)
				float4 color = tex2D(_MainTex, input.uv);
				float3 volumePos = (( - / volumeParams.w) * volumeResolution;

				int3 volumeCoords;
				volumeCoords.x = int(volumePos.x); 
				volumeCoords.y = int(volumePos.y); 
				volumeCoords.z = int(volumePos.z); 
				volumeTex[volumeCoords] = color;
	Fallback Off

This is what I am trying to do, and it doesn’t seem to work, but if I try and write to a 2D texture, it does. Not sure where I am messing it up.


I found that I needed to clear the random write targets AFTER doing my rendering:

Graphics.SetRandomWriteTarget(1, volumeTexture);


This has worked from Unity 4.3