[Unity3D Daily] Use Unity3D screenshots

I. Introduction

Let's see how to take a screenshot

Second, the effect

Insert picture description here
Insert picture description here

Third, the code

using UnityEngine;

public class Screenshot : MonoBehaviour
{
    //截图相机
    Camera capCamera;
    //保存图片
    Texture2D screenShot;

    void Start()
    {
        capCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
    }

    void OnGUI()
    {
        if (GUILayout.Button("Show"))
        {
            CaptureCamera();
        }
    }

    void CaptureCamera()
    {
        Rect rect = new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 1f, Screen.height * 1f);
        // 创建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        capCamera.targetTexture = rt;
        capCamera.Render();
        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        //从RenderTexture.active中读取像素
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示  
        capCamera.targetTexture = null;
        //避免重复添加的错误
        RenderTexture.active = null; 

        //销毁这个对象
        Destroy(rt);

        //保存图片
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.streamingAssetsPath + "/2.png";
        System.IO.File.WriteAllBytes(filename, bytes);
    }
}

Published 226 original articles · praised 509 · 530,000 views

Guess you like

Origin blog.csdn.net/q764424567/article/details/105490112