VolumeControl.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Audio;
  5. public class VolumeControl : MonoBehaviour
  6. {
  7. private AudioListener listener;
  8. private AudioSource source;
  9. private bool isPlay = false;
  10. private float distance = 0;
  11. private float tempdistance = 0;
  12. private AudioMixer mixer;
  13. public float gain=8f;//空间音效的音量增益
  14. public bool isLogartiehmic=false;//是否用对数衰减
  15. // Start is called before the first frame update
  16. void Start()
  17. {
  18. listener = SvrManager.Instance.head.gameObject.GetComponent<AudioListener>();
  19. source = GetComponent<AudioSource>();
  20. if (source.spatialize)
  21. {
  22. mixer = source.outputAudioMixerGroup.audioMixer;
  23. mixer.SetFloat("gain", gain);
  24. }
  25. }
  26. // Update is called once per frame
  27. void Update()
  28. {
  29. if (isPlay && !isLogartiehmic)
  30. {
  31. distance = Vector3.Distance(listener.transform.position, source.transform.position);
  32. if (distance <= 1)
  33. {
  34. source.volume = 1;
  35. }
  36. else if (distance > 1 && distance <= 100)
  37. {
  38. source.volume = 1 / (distance * distance);
  39. }
  40. else if (distance > 100)
  41. {
  42. source.volume = 0;
  43. }
  44. }
  45. }
  46. public void ClickBtn()
  47. {
  48. if (isPlay)
  49. {
  50. isPlay = false;
  51. source.Pause();
  52. }
  53. else
  54. {
  55. isPlay = true;
  56. source.Play();
  57. }
  58. }
  59. private void OnDestroy()
  60. {
  61. listener = null;
  62. mixer = null;
  63. source.enabled = false;
  64. source = null;
  65. }
  66. }