将RenderTexture转换为Texture2D

时间:2017-05-30 14:03:38

标签: c# unity3d io export

我需要将一个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);
    }
}

1 个答案:

答案 0 :(得分:7)

创建新Texture2D,使用RenderTexture.ReadPixelsRenderTexture中的像素读入新Texture2D。最后,请致电Texture2D.Apply();以应用更改的像素。

Texture2D toTexture2D(RenderTexture rTex)
{
    Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
    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);

您可以将其作为扩展方法:

public static class ExtensionMethod
{
    public static Texture2D toTexture2D(this RenderTexture rTex)
    {
        Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
        RenderTexture.active = rTex;
        tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
        tex.Apply();
        return tex;
    }
}

用法:

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