将 RenderTexture 转换为 Texture2D

Convert RenderTexture to Texture2D

我需要将 RenderTexture 对象保存到 .png 文件,然后将其用作纹理来包裹 3D 对象。我的问题是现在我无法使用 EncodeToPNG() 保存 RenderTexture 对象,因为 RenderTexture 不包含该方法。如何将 RenderTexture 对象转换为 Texture2D 对象?谢谢!

// Saves texture as PNG file.
using UnityEngine;
using System.Collections;
using System.IO;

public class SaveTexture : MonoBehaviour {

    public RenderTexture tex;

    // Save Texture as PNG
    void SaveTexturePNG()
    {
        // Encode texture into PNG
        byte[] bytes = tex.EncodeToPNG();
        Object.Destroy(tex);

        // For testing purposes, also write to a file in the project folder
        File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
    }
}

创建新的Texture2D,使用RenderTexture.ReadPixelsRenderTexture读取像素到新的Texture2D。最后,调用 Texture2D.Apply(); 应用更改后的像素。

Texture2D toTexture2D(RenderTexture rTex)
{
    Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
    // ReadPixels looks at the active RenderTexture.
    RenderTexture.active = rTex;
    tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
    tex.Apply();
    return tex;
}

用法:

public RenderTexture tex;
Texture2D myTexture = toTexture2D(tex);

你可以让它成为一个扩展方法(恢复之前活跃的RenderTexture以避免意外):

public static class ExtensionMethod
{
    public static Texture2D toTexture2D(this RenderTexture rTex)
    {
        Texture2D tex = new Texture2D(rTex.width, rTex.height, TextureFormat.RGB24, false);
        var old_rt = RenderTexture.active;
        RenderTexture.active = rTex;

        tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
        tex.Apply();

        RenderTexture.active = old_rt;
        return tex;
    }
}

用法:

public RenderTexture tex;
Texture2D myTexture = tex.toTexture2D();