Unity3D で RenderTexture を使用してゲーム内のスクリーンショットを実現する

1 System.Collections を使用します2  System.Collections.Generic
を使用します。3 System.IOを使用します4 UnityEngineを使用する5 6 public class截图 : MonoBehaviour {
 7 8 private void Update()
 9     {
 10 if (Input.GetKeyDown(KeyCode.S))
 11         {
 12              Debug.Log( " Save " );
13            保存();
14         }
 15     }
 16 17   
   
                     
     プライベートRenderTexture TargetTexture;
18  
19      private  void OnRenderImage(RenderTexture ソース、RenderTexture 宛先)
 20      {
 21          TargetTexture =ソース;
22          Graphics.Blit(ソース、宛先);
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         バイト[] バイト = png.EncodeToPNG();
33         文字列パス =文字列.Format( @" D:\123.png " );
34          FileStream ファイル = File.Open(path, FileMode.Create);
35          BinaryWriter ライター =新しいBinaryWriter(ファイル);
36         ライター.書き込み(バイト);
37         ファイル.Close();
38         ライター.Close();
39  
40         破壊(png);
41          png = null ;
42          
43          Debug.Log( "上に保存" );
44      }
 45 }

関数:

S をクリックしてスクリーンショットを撮ります。

このスクリプトはカメラにマウントする必要があります。

OnRenderImage は Unity の組み込みイベントで、GPU がシーンをレンダリングした後、画面にレンダリングする前に実行されます。2 つのパラメーター。1 つは GPU によってレンダリングされるイメージで、2 番目のパラメーターはイベントの呼び出し後に画面にレンダリングされます。

このイベントは画面後の処理に使用できますが、ここではレンダリングされたイメージをインターセプトし、保存してから返すために使用します。

転載先:https://www.cnblogs.com/Yukisora/p/8885202.html

おすすめ

転載: blog.csdn.net/a1808508751/article/details/101353099