1.RenderTexture->Texture2D
异步:
IEnumerator Start() { var rt = new RenderTexture(512, 512, 0); //Graphics.xxx... var req = AsyncGPUReadback.Request(rt); yield return new WaitUntil(() => req.done); var tex = new Texture2D(512, 512, TextureFormat.RGBA32, false); var colorArray = req.GetData<Color32>().ToArray(); tex.SetPixels32(colorArray); tex.Apply(); }
同步:
RenderTexture.active = rt; var tex = new Texture2D(512, 512, TextureFormat.RGBA32, false); tex.ReadPixels(new Rect(0, 0, 512, 512), 0, 0, false); tex.Apply();
2.AsyncGPUReadback GetData
cs:
#pragma kernel CSMain struct TestData { float3 pos; }; RWStructuredBuffer<TestData> MyData; [numthreads(8,1,1)] void CSMain (uint3 id : SV_DispatchThreadID) { MyData[id.x].pos = MyData[id.x].pos * 2; }
异步:
public class ComputeShaderAsyncRequest : MonoBehaviour { public struct TestData { public Vector3 pos; } public ComputeShader computeShader; IEnumerator Start() { var kernelID = computeShader.FindKernel("CSMain"); var testData = new List<TestData>(); for (int i = 0; i < 64; i++) testData.Add(new TestData() { pos = new Vector3(i, 0, 0) }); var computeBuffer = new ComputeBuffer(testData.Count, 12); computeBuffer.SetData(testData); computeShader.SetBuffer(kernelID, "MyData", computeBuffer); computeShader.Dispatch(kernelID, 8, 1, 1); var request = AsyncGPUReadback.Request(computeBuffer); Debug.Log("frame1: " + Time.frameCount);//1 yield return new WaitUntil(() => request.done); Debug.Log("frame2: " + Time.frameCount);//4 var testDataArray = request.GetData<TestData>().ToArray(); for (int i = 0; i < testDataArray.Length; i++) Debug.Log("i :" + i + "item: " + testDataArray[i].pos); } }
同步:
public class ComputeShaderAsyncRequest_Sync : MonoBehaviour { public struct TestData { public Vector3 pos; } public ComputeShader computeShader; void Start() { var kernelID = computeShader.FindKernel("CSMain"); var testData = new List<TestData>(); for (int i = 0; i < 64; i++) testData.Add(new TestData() { pos = new Vector3(i, 0, 0) }); var computeBuffer = new ComputeBuffer(testData.Count, 12); computeBuffer.SetData(testData); computeShader.SetBuffer(kernelID, "MyData", computeBuffer); computeShader.Dispatch(kernelID, 8, 1, 1); var array = new TestData[testData.Count]; computeBuffer.GetData(array); for (int i = 0; i < array.Length; i++) Debug.Log("i :" + i + "item: " + array[i].pos); } }
转载:https://www.cnblogs.com/hont/p/11351273.html