Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. #if UNITY_EDITOR
  5. using UnityEditor;
  6. #endif
  7.  
  8. public class Fade : MonoBehaviour
  9. {
  10. float _time;
  11. float _elapsed;
  12.  
  13. Texture2D _fadeTex;
  14. Material _fadeMat;
  15. Color _color;
  16. bool _fadeIn = false;
  17.  
  18. void Awake()
  19. {
  20. var shader = Shader.Find("Particles/Alpha Blended");
  21. _fadeMat = new Material(shader);
  22. _fadeTex = new Texture2D(1, 1);
  23. _fadeTex.SetPixel(0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f));
  24. _fadeTex.Apply();
  25.  
  26. _fadeMat.color = Color.black;
  27.  
  28. _time = 1.0f;
  29. _elapsed = 0.0f;
  30. _color = Color.black;
  31. enabled = false;
  32. }
  33.  
  34. void Destroy()
  35. {
  36. #if UNITY_EDITOR
  37. DestroyImmediate(_fadeTex);
  38. DestroyImmediate(_fadeMat);
  39. #elif
  40. Destroy(_fadeTex);
  41. Destroy(_fadeMat);
  42. #endif
  43. }
  44.  
  45. public void FadeIn(float time)
  46. {
  47. enabled = true;
  48. _time = time;
  49. _elapsed = 0.0f;
  50. _fadeIn = true;
  51. }
  52.  
  53. public void FadeOut(float time)
  54. {
  55. enabled = true;
  56. _time = time;
  57. _elapsed = 0.0f;
  58. _fadeIn = false;
  59. }
  60.  
  61. void OnPostRender()
  62. {
  63. float t = Mathf.Clamp01(_elapsed / _time);
  64. _color.a = _fadeIn ? 1.0f - t : t;
  65. _fadeMat.SetColor("_TintColor", _color);
  66. Graphics.Blit(_fadeTex, _fadeMat);
  67.  
  68. if (_time > _elapsed)
  69. {
  70. _elapsed += Time.deltaTime;
  71. }
  72. }
  73.  
  74. #if UNITY_EDITOR
  75. [CustomEditor(typeof(Fade))]
  76. class FadeInspector : Editor
  77. {
  78. public override void OnInspectorGUI()
  79. {
  80. if (GUILayout.Button("Fade In"))
  81. {
  82. var fade = (Fade)target;
  83. fade.FadeIn(1.0f);
  84. }
  85.  
  86. if (GUILayout.Button("Fade Out"))
  87. {
  88. var fade = (Fade)target;
  89. fade.FadeOut(1.0f);
  90. }
  91. }
  92. }
  93. #endif
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement