Use ChatGPT to write a code piece that captures the current scene in Unity and saves it locally

Here is GPT's answer:

In this code, we use RenderTexture to capture the image rendered by the camera. There are two benefits to using RenderTexture. First, it allows us to capture the image rendered by the camera instead of the entire screen. Second, we can read image data through RenderTexture instead of reading data directly from the screen. In the Update method, we detect if the S key was pressed, and if so, do the following:

  1. Create a RenderTexture object and set it as the current camera's target texture.
  2. Create a Texture2D object, and read the pixel data in the RenderTexture object into the Texture2D object.
  3. Reset the camera's target texture and destroy the RenderTexture object.
  4. Convert the Texture2D object to a byte array in PNG format and save it to a local file.

Note that we save the image to the application data folder. This is because we can't save the image directly into the project folder, we have to save it to the application data folder or somewhere else.

using UnityEngine;
using System.IO;

public class ScreenShot : MonoBehaviour
{
    
    
    public int captureWidth = 1920;
    public int captureHeight = 1080;
    private Camera mainCamera;

    void Start()
    {
    
    
        mainCamera = Camera.main;
    }

    void Update()
    {
    
    
        if (Input.GetKeyDown(KeyCode.S))
        {
    
    
            string fileName = "screenshot.png";
            string path = Path.Combine(Application.dataPath, fileName);

            RenderTexture rt = new RenderTexture(captureWidth, captureHeight, 24);
            mainCamera.targetTexture = rt;
            Texture2D screenShot = new Texture2D(captureWidth, captureHeight, TextureFormat.RGB24, false);
            mainCamera.Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, captureWidth, captureHeight), 0, 0);
            mainCamera.targetTexture = null;
            RenderTexture.active = null;
            Destroy(rt);

            byte[] bytes = screenShot.EncodeToPNG();
            File.WriteAllBytes(path, bytes);
            Debug.Log("Screenshot saved to " + path);
        }
    }
}

おすすめ

転載: blog.csdn.net/Czhenya/article/details/130061753