FlowFadeOut.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using UnityEngine;
  2. using UnityEngine.Events;
  3. using CW.Common;
  4. namespace FLOW
  5. {
  6. /// <summary>This component fades out the first material's Color.a to 0.</summary>
  7. [RequireComponent(typeof(Renderer))]
  8. [HelpURL(FlowCommon.HelpUrlPrefix + "FlowFadeOut")]
  9. [AddComponentMenu(FlowCommon.ComponentMenuPrefix + "Fade Out")]
  10. public class FlowFadeOut : MonoBehaviour
  11. {
  12. /// <summary>The time the fade out takes in seconds.</summary>
  13. public float Duration { set { duration = value; } get { return duration; } } [SerializeField] private float duration = 1.0f;
  14. /// <summary>The maximum opacity that will be faded from.</summary>
  15. public float Opacity { set { opacity = value; } get { return opacity; } } [SerializeField] private float opacity = 0.5f;
  16. /// <summary>This event is invoked when the fade out finishes.</summary>
  17. public UnityEvent OnFinished { get { if (onFinished == null) onFinished = new UnityEvent(); return onFinished; } } [SerializeField] private UnityEvent onFinished;
  18. [System.NonSerialized]
  19. private Material cachedMaterial;
  20. [SerializeField]
  21. private float alpha;
  22. protected virtual void OnEnable()
  23. {
  24. alpha = 1.0f;
  25. UpdateAlpha();
  26. }
  27. protected virtual void Update()
  28. {
  29. if (alpha > 0.0f)
  30. {
  31. var delta = 1.0f / Mathf.Max(duration, 0.01f);
  32. alpha = Mathf.MoveTowards(alpha, 0.0f, delta * Time.deltaTime);
  33. UpdateAlpha();
  34. if (alpha == 0.0f)
  35. {
  36. if (onFinished != null)
  37. {
  38. onFinished.Invoke();
  39. }
  40. }
  41. }
  42. }
  43. private void UpdateAlpha()
  44. {
  45. if (cachedMaterial == null)
  46. {
  47. cachedMaterial = GetComponent<Renderer>().material;
  48. }
  49. if (cachedMaterial != null)
  50. {
  51. var color = cachedMaterial.color;
  52. color.a = 1.0f - Mathf.Sqrt(1.0f - Mathf.Pow(alpha, 2.0f));
  53. color.a *= opacity;
  54. cachedMaterial.color = color;
  55. }
  56. }
  57. }
  58. }
  59. #if UNITY_EDITOR
  60. namespace FLOW
  61. {
  62. using UnityEditor;
  63. using TARGET = FlowFadeOut;
  64. [CanEditMultipleObjects]
  65. [CustomEditor(typeof(TARGET))]
  66. public class FlowFadeOut_Editor : CwEditor
  67. {
  68. protected override void OnInspector()
  69. {
  70. TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
  71. Draw("duration", "The time the fade out takes in seconds.");
  72. Draw("opacity", "The maximum opacity that will be faded from.");
  73. Separator();
  74. Draw("onFinished");
  75. }
  76. }
  77. }
  78. #endif