VolumeControl.cs 2.0 KB

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