Tanoda
ScreenshotGenerator.cs
Go to the documentation of this file.
1using System.Collections;
2using System.Collections.Generic;
3using System.Runtime.InteropServices;
4using UnityEngine;
5
6public class ScreenshotGenerator : MonoBehaviour
7{
8 public GameObject[] HideInScreenshots;
9 #if UNITY_WEBGL
10 [DllImport("__Internal")]
11 private static extern void DownloadFile(byte[] array, int byteLength, string fileName);
12 #endif
13 private int screenshotCounter = 0;
14
15 public void ScreenshotNow()
16 {
17 var cam = Camera.main;
18
19 foreach (var o in HideInScreenshots)
20 {
21 if (o.GetComponent<Canvas>())
22 {
23 o.GetComponent<Canvas>().enabled = false;
24 }
25 else
26 {
27 o.SetActive(false);
28 }
29 }
30 var picBytes = TakeScreenShot(1024, 768, cam);
31
32 foreach (var o in HideInScreenshots)
33 {
34 if (o.GetComponent<Canvas>())
35 {
36 o.GetComponent<Canvas>().enabled = true;
37 }
38 else
39 {
40 o.SetActive(true);
41 }
42 }
43
44 screenshotCounter++;
45#if UNITY_WEBGL
46 //DownloadFile(picBytes, picBytes.Length, $"screenshot{screenshotCounter}.png");
47 StartCoroutine(NetworkManager.instance.UploadScreenshotCourse(picBytes, () => { PopupManager.instance.ShowPopup("SUCCESS", "UPLOAD_SUCCESS"); }, () => { PopupManager.instance.ShowPopup("UPLOAD_ERROR", "UPLOAD_ERROR_TEXT"); }));
48#endif
49 }
50
51 public static byte[] TakeScreenShot(int width, int height, Camera camera)
52 {
53 // render camera with specified resolution
54 var renderTexture = new RenderTexture(width, height, 24);
55 camera.targetTexture = renderTexture;
56 camera.Render();
57 RenderTexture.active = renderTexture;
58
59 // store in image
60 var screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);
61 screenShot.ReadPixels(new Rect(0, 0, width, height), 0, 0);
62
63 // clean up
64 camera.targetTexture = null;
65 RenderTexture.active = null;
66
67#if UNITY_EDITOR
68 DestroyImmediate(renderTexture);
69#else
70 Destroy(renderTexture);
71#endif
72
73 return screenShot.EncodeToPNG();
74 }
75}
static byte[] TakeScreenShot(int width, int height, Camera camera)
GameObject[] HideInScreenshots