1+ using UnityEngine ;
2+ using UnityEngine . UI ;
3+ using UnityEditor ;
4+ using System . Collections ;
5+
6+ public class ScreenShotScript : MonoBehaviour {
7+
8+ public AudioSource audio ;
9+ public RawImage screenShot ;
10+
11+ private Texture2D screenShotTexture ;
12+ private string lastScreenShotPath ;
13+
14+ // Use this for initialization
15+ void Start ( ) {
16+ screenShotTexture = new Texture2D ( 100 , 100 ) ;
17+ screenShot . texture = screenShotTexture ;
18+ }
19+
20+ // Update is called once per frame
21+ void Update ( ) {
22+
23+ }
24+
25+ void TakeScreenShot ( string path ) {
26+ StartCoroutine ( CaptureScreen ( path ) ) ;
27+ }
28+
29+ IEnumerator CaptureScreen ( string path ) {
30+ // Wait till the last possible moment before screen rendering to hide the UI
31+ yield return null ;
32+ // GameObject.Find("UICanvas").GetComponent<Canvas>().enabled = false;
33+
34+ // Wait for screen rendering to complete
35+ yield return new WaitForEndOfFrame ( ) ;
36+
37+ // Take screenshot
38+ Application . CaptureScreenshot ( path ) ;
39+
40+ // Show UI after we're done
41+ // GameObject.Find("UICanvas").GetComponent<Canvas>().enabled = true;
42+ }
43+
44+ void OnGUI ( ) {
45+ Event e = Event . current ;
46+
47+ if ( e . type == EventType . KeyDown && e . keyCode == KeyCode . F ) {
48+ string current_time = System . DateTime . Now . ToString ( ) . Replace ( "/" , "_" ) . Replace ( ":" , "_" ) ;
49+ lastScreenShotPath = FileUtil . GetUniqueTempPathInProject ( ) + current_time + ".png" ;
50+ Debug . Log ( "saved: " + lastScreenShotPath ) ;
51+ TakeScreenShot ( lastScreenShotPath ) ;
52+
53+ audio . Play ( ) ;
54+ Debug . Log ( "Screenshot" ) ;
55+
56+ }
57+ }
58+
59+ void LateUpdate ( ) {
60+ StartCoroutine ( DisplayScreenShot ( ) ) ;
61+ }
62+
63+ IEnumerator DisplayScreenShot ( ) {
64+ yield return null ;
65+
66+ if ( System . IO . File . Exists ( lastScreenShotPath ) ) {
67+ Debug . Log ( "File found!" ) ;
68+ var screenShotBytes = System . IO . File . ReadAllBytes ( lastScreenShotPath ) ;
69+ screenShotTexture . LoadImage ( screenShotBytes ) ;
70+ screenShot . material . mainTexture = screenShotTexture ;
71+ }
72+ }
73+ }
0 commit comments