是否可以使用计算着色器来使用变量和函数,例如#include“UnityCG.cginc”中的UNITY_MATRIX_MVP 下面的代码会返回0并报错:
CG:
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain
#include "UnityCG.cginc"
RWStructuredBuffer<float> Result;
[numthreads(1,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
Result[id.x] = UNITY_MATRIX_MVP[0][0];
}
C#
...
public ComputeShader _ComputeShader;
void Start()
{
kernelIndex = _ComputeShader.FindKernel("CSMain");
_Result = new ComputeBuffer(1, 4);
_ComputeShader.SetBuffer(kernelIndex, "Result", _Result);
_ComputeShader.Dispatch(kernelIndex, 1, 1, 1);
float[] total = new float[1];
_Result.GetData(total);
Debug.Log(total[0]);
}
...
错误:“NewComputeShader.compute”中的着色器错误:所有内核必须使用相同的常量缓冲区布局;发现“unity_LightColor0”属性不同 我可以在计算着色器中使用 UnityCG.cginc 吗? 版本:Unity 2019.4.23f1c1
我找到了解决此问题的方法:在 C# 脚本中计算 MVP 并将其设置为计算着色器。
void OnRenderObject()
{
// UNITY_MATRIX_MVP
Camera cam = Camera.current;
//Matrix4x4 p = cam.projectionMatrix;
Matrix4x4 p = GL.GetGPUProjectionMatrix(cam.projectionMatrix, true);
Matrix4x4 v = cam.worldToCameraMatrix;
Matrix4x4 m = gameObject.transform.localToWorldMatrix;
Matrix4x4 MVP = p * v * m;
shaderPreprocess.SetMatrix("_UNITY_MATRIX_MVP", MVP);
}
注意事项:
Camera.current
指向当前查看摄像机,在编辑器摄像机和 Camera.main
之间切换。Camera.current
在 OnRenderObject()
中稳定,所以我将代码放在这里。 Update()
不稳定。如果你不关心编辑器的预览,你可以使用 Camera.main
并将代码放在 Update()
中。true
中的GL.GetGPUProjectionMatrix(cam.projectionMatrix, true)
导致Y轴翻转。float4x4 _UNITY_MATRIX_MVP;