Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将RenderTexture转换为Texture2D_C#_Unity3d_Io_Export - Fatal编程技术网

C# 将RenderTexture转换为Texture2D

C# 将RenderTexture转换为Texture2D,c#,unity3d,io,export,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; pu

我需要将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.ReadPixels
将像素从
RenderTexture
读取到新的
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);
public RenderTexture tex;
Texture2D myTexture = tex.toTexture2D();

您可以将其作为扩展方法(还原以前的活动渲染器以避免意外):

用法:

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

为什么需要将rTex设置为RenderTexture.active?@ErayTuncer
Texture2D。ReadPixels
将从当前活动的
RenderTexture
复制一个矩形像素区域,并将其存储在
Texture2D/tex
中。最好阅读此答案中使用的每个属性函数的文档。您可能需要存储现有的
RenderTexture
,然后将其还原。