AudioUtils.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace HQFPSWeapons
  5. {
  6. /// <summary>
  7. ///
  8. /// </summary>
  9. public class AudioUtils : Singleton<AudioUtils>
  10. {
  11. public Value<Gunshot> LastGunshot = new Value<Gunshot>(null);
  12. private Dictionary<AudioSource, Coroutine> m_LevelSetters = new Dictionary<AudioSource, Coroutine>();
  13. [SerializeField]
  14. private AudioSource m_2DAudioSource = null;
  15. public void Play2D(AudioClip clip, float volume)
  16. {
  17. if(m_2DAudioSource)
  18. m_2DAudioSource.PlayOneShot(clip, volume);
  19. }
  20. /// <summary>
  21. ///
  22. /// </summary>
  23. public static AudioSource CreateAudioSource(string name, Transform parent, Vector3 localPosition, bool is2D = false, float startVolume = 1f, float minDistance = 1f)
  24. {
  25. GameObject audioObject = new GameObject(name, typeof(AudioSource));
  26. audioObject.transform.parent = parent;
  27. audioObject.transform.localPosition = localPosition;
  28. AudioSource audioSource = audioObject.GetComponent<AudioSource>();
  29. audioSource.volume = startVolume;
  30. audioSource.spatialBlend = is2D ? 0f : 1f;
  31. audioSource.minDistance = minDistance;
  32. return audioSource;
  33. }
  34. /// <summary>
  35. ///
  36. /// </summary>
  37. public void LerpVolumeOverTime(AudioSource audioSource, float targetVolume, float speed)
  38. {
  39. if(m_LevelSetters.ContainsKey(audioSource))
  40. {
  41. if(m_LevelSetters[audioSource] != null)
  42. StopCoroutine(m_LevelSetters[audioSource]);
  43. m_LevelSetters[audioSource] = StartCoroutine(C_LerpVolumeOverTime(audioSource, targetVolume, speed));
  44. }
  45. else
  46. m_LevelSetters.Add(audioSource, StartCoroutine(C_LerpVolumeOverTime(audioSource, targetVolume, speed)));
  47. }
  48. /// <summary>
  49. ///
  50. /// </summary>
  51. private IEnumerator C_LerpVolumeOverTime(AudioSource audioSource, float volume, float speed)
  52. {
  53. while(audioSource != null && Mathf.Abs(audioSource.volume - volume) > 0.01f)
  54. {
  55. audioSource.volume = Mathf.MoveTowards(audioSource.volume, volume, Time.deltaTime * speed);
  56. yield return null;
  57. }
  58. if(audioSource.volume == 0f)
  59. audioSource.Stop();
  60. m_LevelSetters.Remove(audioSource);
  61. }
  62. }
  63. public class Gunshot
  64. {
  65. public Vector3 Position { get; private set; }
  66. public LivingEntity EntityThatShot { get; private set; }
  67. public Gunshot(Vector3 position, LivingEntity entityThatShot = null)
  68. {
  69. Position = position;
  70. EntityThatShot = entityThatShot;
  71. }
  72. }
  73. }