Shamba

Flash

Jun 7th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4.  
  5. public class Flash : MonoBehaviour
  6. {
  7.     ///////////////////////////////////////////////////
  8.     public float flashTimelength = .2f;
  9.     public bool doCameraFlash = false;
  10.  
  11.     ///////////////////////////////////////////////////
  12.     private Image flashImage;
  13.     private float startTime;
  14.     private bool flashing = false;
  15.  
  16.     ///////////////////////////////////////////////////
  17.     void Start()
  18.     {
  19.         flashImage = GetComponent<Image>();
  20.         Color col = flashImage.color;
  21.         col.a = 0.0f;
  22.         flashImage.color = col;
  23.     }
  24.  
  25.     ///////////////////////////////////////////////////
  26.     void Update()
  27.     {
  28.         if (doCameraFlash && !flashing)
  29.         {
  30.             CameraFlash();
  31.         }
  32.         else
  33.         {
  34.             doCameraFlash = false;
  35.         }
  36.     }
  37.  
  38.     ///////////////////////////////////////////////////
  39.     public void CameraFlash()
  40.     {
  41.         // initial color
  42.         Color col = flashImage.color;
  43.  
  44.         // start time to fade over time
  45.         startTime = Time.time;
  46.  
  47.         // so we can flash again
  48.         doCameraFlash = false;
  49.  
  50.         // start it as alpha = 1.0 (opaque)
  51.         col.a = 1.0f;
  52.  
  53.         // flash image start color
  54.         flashImage.color = col;
  55.  
  56.         // flag we are flashing so user can't do 2 of them
  57.         flashing = true;
  58.  
  59.         StartCoroutine(FlashCoroutine());
  60.     }
  61.  
  62.     ///////////////////////////////////////////////////
  63.     IEnumerator FlashCoroutine()
  64.     {
  65.         bool done = false;
  66.  
  67.         while (!done)
  68.         {
  69.             float perc;
  70.             Color col = flashImage.color;
  71.  
  72.             perc = Time.time - startTime;
  73.             perc = perc / flashTimelength;
  74.  
  75.             if (perc > 1.0f)
  76.             {
  77.                 perc = 1.0f;
  78.                 done = true;
  79.             }
  80.  
  81.             col.a = Mathf.Lerp(1.0f, 0.0f, perc);
  82.             flashImage.color = col;
  83.             flashing = true;
  84.  
  85.             yield return null;
  86.         }
  87.  
  88.         flashing = false;
  89.  
  90.         yield break;
  91.     }
  92. }
Add Comment
Please, Sign In to add comment