Use RenderTexture in Unity3D to achieve in-game screenshots

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using UnityEngine;
 5 
 6 public class 截图 : MonoBehaviour {
 7 
 8     private void Update()
 9     {
10         if(Input.GetKeyDown(KeyCode.S))
11         {
12             Debug.Log("Save");
13             Save();
14         }
15     }
16 
17     private RenderTexture TargetTexture;
18 
19     private void OnRenderImage(RenderTexture source, RenderTexture destination)
20     {
21         TargetTexture = source;
22         Graphics.Blit(source, destination);
23     }
24 
25     private void Save()
26     {
27         RenderTexture.active = TargetTexture;
28 
29         Texture2D png = new Texture2D(RenderTexture.active.width, RenderTexture.active.height, TextureFormat.ARGB32, true);
30         png.ReadPixels(new Rect(0, 0, RenderTexture.active.width, RenderTexture.active.height), 0, 0);
31 
32         byte[] bytes = png.EncodeToPNG();
33         string path = string.Format(@"D:\123.png");
34         FileStream file = File.Open(path, FileMode.Create);
35         BinaryWriter writer = new BinaryWriter(file);
36         writer.Write(bytes);
37         file.Close();
38         writer.Close();
39 
40         Destroy(png);
41         png = null;
42         
43         Debug.Log("Save Down");
44     }
45 }

Function:

Click S to take a screenshot.

This script needs to be mounted on the camera.

OnRenderImage is a built-in event of Unity, which will be executed after the GPU renders the scene and before rendering to the screen. Two parameters, one is the image rendered by the GPU, and the second parameter will be rendered to the screen after the event is called.

This event can be used for post-screen processing, but we use it here to intercept the rendered image, save it and then return it.

Reprinted in: https://www.cnblogs.com/Yukisora/p/8885202.html

Guess you like

Origin blog.csdn.net/a1808508751/article/details/101353099