如何在 Unity 中将纹理直接渲染到相机

How does one Render a texture directly to the Camera in Unity

在 Unity 中,我有 2 个纹理形式的图像,我将它们合并在一起(一个覆盖另一个)。我在 Compute Shader 中执行此操作并将结果放在 RenderTexture 中。我希望这个 RenderTexture 是输出相机看到的一切。

我发现文章说要使用相机的 ReplacementShader 属性,但我无法让它正常工作。

目前我只是简单地将RenderTexture放到覆盖整个UICanvas的UIRawImage上,这样就可以填满整个相机。然而,这有很多滞后,显然是一个次优的解决方案。

那么如何将 Rendertexture 或计算 Shader 结果直接输出到相机上。谢谢。

你或许可以使用 OnRenderImage

Event function that Unity calls after a Camera has finished rendering, that allows you to modify the Camera's final image.

并使用Graphics.Blit

Copies source texture into destination render texture with a shader.

然后做一些事情,例如

// This script goes onto your according Camera
public class RenderReplacement : MonoBehaviour
{
    public RenderTexture replacement;

    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        // To overwrite the entire screen
        Graphics.Blit(replacement, null);

        // Or to overwrite only what this specific Camera renders
        //Graphics.Blit(replacement, dest);
    }
}

在哪里

dest
The destination RenderTexture. Set this to null to blit directly to screen. See description for more information.


请注意,如 API 中所述,OnRenderImage 在 此相机已完成渲染后被调用 。因此,为了提高效率——因为我们基本上放弃了渲染——只需通过禁用所有层来确保相机基本上不渲染任何东西,例如让它只渲染单色背景