抓取unity相机直接导出为图片的方法

挂载物体需拥有camera组件,并且targetTexture需要赋值

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CatchCamera : MonoBehaviour
{
    public RenderTexture texture;
    public Texture2D texture2D;
    public new Camera camera;

    [ContextMenu("Export")]
    void Export()
    {
        camera = GetComponent<Camera>();
        texture = camera.targetTexture;
        RenderTexture currentActiveRT = RenderTexture.active;
        RenderTexture.active = texture;
        texture2D = new Texture2D(texture.width, texture.height, TextureFormat.ARGB32, false);
        texture2D.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
        var bytes = texture2D.EncodeToPNG();
        System.IO.File.WriteAllBytes("1.png", bytes);
    }
}
 

猜你喜欢

转载自blog.csdn.net/weixin_49494690/article/details/126433291