Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- #if UNITY_EDITOR
- using UnityEditor;
- #endif
- public class Fade : MonoBehaviour
- {
- float _time;
- float _elapsed;
- Texture2D _fadeTex;
- Material _fadeMat;
- Color _color;
- bool _fadeIn = false;
- void Awake()
- {
- var shader = Shader.Find("Particles/Alpha Blended");
- _fadeMat = new Material(shader);
- _fadeTex = new Texture2D(1, 1);
- _fadeTex.SetPixel(0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f));
- _fadeTex.Apply();
- _fadeMat.color = Color.black;
- _time = 1.0f;
- _elapsed = 0.0f;
- _color = Color.black;
- enabled = false;
- }
- void Destroy()
- {
- #if UNITY_EDITOR
- DestroyImmediate(_fadeTex);
- DestroyImmediate(_fadeMat);
- #elif
- Destroy(_fadeTex);
- Destroy(_fadeMat);
- #endif
- }
- public void FadeIn(float time)
- {
- enabled = true;
- _time = time;
- _elapsed = 0.0f;
- _fadeIn = true;
- }
- public void FadeOut(float time)
- {
- enabled = true;
- _time = time;
- _elapsed = 0.0f;
- _fadeIn = false;
- }
- void OnPostRender()
- {
- float t = Mathf.Clamp01(_elapsed / _time);
- _color.a = _fadeIn ? 1.0f - t : t;
- _fadeMat.SetColor("_TintColor", _color);
- Graphics.Blit(_fadeTex, _fadeMat);
- if (_time > _elapsed)
- {
- _elapsed += Time.deltaTime;
- }
- }
- #if UNITY_EDITOR
- [CustomEditor(typeof(Fade))]
- class FadeInspector : Editor
- {
- public override void OnInspectorGUI()
- {
- if (GUILayout.Button("Fade In"))
- {
- var fade = (Fade)target;
- fade.FadeIn(1.0f);
- }
- if (GUILayout.Button("Fade Out"))
- {
- var fade = (Fade)target;
- fade.FadeOut(1.0f);
- }
- }
- }
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement