我需要将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();

10-06 12:06