[text] Capture

Viewer

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class PhotoCapture : MonoBehaviour
  6. {
  7.     [Header("Photo Taker")]
  8.     [SerializeField] private Image photoDisplayArea;
  9.     [SerializeField] private GameObject photoFrame;
  10.     [SerializeField] private GameObject cameraUI;
  11.  
  12.     [Header("Flash Effect")]
  13.     [SerializeField] private GameObject cameraFlash;
  14.     [SerializeField] private float flashTime;
  15.  
  16.     [Header("Photo Fader Effect")]
  17.     [SerializeField] private Animator fadingAnimation;
  18.  
  19.     [Header("Audio")]
  20.     [SerializeField] private AudioSource cameraAudio;
  21.  
  22.     private Texture2D screenCapture;
  23.     private bool viewingPhoto;
  24.     private bool isCaptureingPhoto;
  25.  
  26.     private void Start()
  27.     {
  28.         screenCapture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
  29.     }
  30.     public void OnClick(bool isPhotoMode)
  31.     {
  32.         if (isPhotoMode && viewingPhoto)
  33.         {
  34.             RemovePhoto();
  35.         }
  36.         if (!isPhotoMode)
  37.         {
  38.             RemovePhoto();
  39.         }
  40.         if (!viewingPhoto)
  41.         {
  42.             StartCoroutine(CapturePhoto());   
  43.         }
  44.     }
  45.     IEnumerator CapturePhoto()
  46.     {//alt enter
  47.         if (isCaptureingPhoto) yield break; //cantspam
  48.         cameraUI.SetActive(false);
  49.         isCaptureingPhoto = true;
  50.         viewingPhoto = true; 
  51.  
  52.         yield return new WaitForEndOfFrame();
  53.  
  54.         Rect regionToRead = new Rect(0, 0, Screen.width, Screen.height);
  55.  
  56.         screenCapture.ReadPixels(regionToRead, 0, 0, false);
  57.         screenCapture.Apply();
  58.         ShowPhoto();
  59.     }
  60.  
  61.     void ShowPhoto()
  62.     {
  63.         Sprite photoSprite = Sprite.Create(screenCapture, new Rect(0.0f, 0.0f, screenCapture.width, screenCapture.height), new Vector2(0.5f, 0.5f), 100.0f);
  64.         photoDisplayArea.sprite = photoSprite;
  65.  
  66.         photoFrame.SetActive(true);
  67.         StartCoroutine(CameraFlashEffect());
  68.         fadingAnimation.Play("CameraAphla");
  69.     }
  70.  
  71.     IEnumerator CameraFlashEffect()
  72.     {
  73.         cameraAudio.Play();
  74.         cameraFlash.SetActive(true);
  75.         yield return new WaitForSeconds(flashTime);
  76.         cameraFlash.SetActive(false);
  77.         isCaptureingPhoto = false;
  78.     }
  79.  
  80.     public void RemovePhoto()
  81.     {
  82.         viewingPhoto = false;
  83.         photoFrame.SetActive(false);
  84.     }
  85. }
  86.  

Editor

You can edit this paste and save as new: