TweenVolume.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //----------------------------------------------
  2. // NGUI: Next-Gen UI kit
  3. // Copyright © 2011-2014 Tasharen Entertainment
  4. //----------------------------------------------
  5. using UnityEngine;
  6. /// <summary>
  7. /// Tween the audio source's volume.
  8. /// </summary>
  9. [RequireComponent(typeof(AudioSource))]
  10. public class TweenVolume : Tweener
  11. {
  12. #if UNITY_3_5
  13. public float from = 1f;
  14. public float to = 1f;
  15. #else
  16. [Range(0f, 1f)] public float from = 1f;
  17. [Range(0f, 1f)] public float to = 1f;
  18. #endif
  19. AudioSource mSource;
  20. /// <summary>
  21. /// Cached version of 'audio', as it's always faster to cache.
  22. /// </summary>
  23. public AudioSource audioSource
  24. {
  25. get
  26. {
  27. if (mSource == null)
  28. {
  29. mSource = GetComponent<AudioSource>();
  30. if (mSource == null)
  31. {
  32. mSource = GetComponent<AudioSource>();
  33. if (mSource == null)
  34. {
  35. Debug.LogError("TweenVolume needs an AudioSource to work with", this);
  36. enabled = false;
  37. }
  38. }
  39. }
  40. return mSource;
  41. }
  42. }
  43. [System.Obsolete("Use 'value' instead")]
  44. public float volume { get { return this.value; } set { this.value = value; } }
  45. /// <summary>
  46. /// Audio source's current volume.
  47. /// </summary>
  48. public float value
  49. {
  50. get
  51. {
  52. return audioSource != null ? mSource.volume : 0f;
  53. }
  54. set
  55. {
  56. if (audioSource != null) mSource.volume = value;
  57. }
  58. }
  59. protected override void OnUpdate (float factor, bool isFinished)
  60. {
  61. value = from * (1f - factor) + to * factor;
  62. //mSource.enabled = (mSource.volume > 0.01f);
  63. }
  64. /// <summary>
  65. /// Start the tweening operation.
  66. /// </summary>
  67. static public TweenVolume Begin (GameObject go, float duration, float targetVolume)
  68. {
  69. TweenVolume comp = Tweener.Begin<TweenVolume>(go, duration);
  70. comp.from = comp.value;
  71. comp.to = targetVolume;
  72. return comp;
  73. }
  74. public override void SetStartToCurrentValue () { from = value; }
  75. public override void SetEndToCurrentValue () { to = value; }
  76. }