You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.7 KiB

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using JetBrains.Annotations;
  5. using UnityEngine;
  6. using Random = UnityEngine.Random;
  7. public class AudioRandomiser : MonoBehaviour
  8. {
  9. public AudioClip[] audioSources;
  10. public HerdController herd;
  11. public GameObject audioPosition;
  12. public float waitTime;
  13. public float[] volumes;
  14. public bool makeSolo;
  15. public bool mute;
  16. [Range(0, 1)]
  17. public float spacialBlend = 1;
  18. // Start is called before the first frame update
  19. void Start()
  20. {
  21. }
  22. void Awake()
  23. {
  24. StartCoroutine(PlayClips());
  25. }
  26. public void PlaySoundFromCount()
  27. {
  28. int count = 1;
  29. if (herd != null)
  30. {
  31. count = (int)Mathf.Round(herd.HerdAmount() / 10);
  32. count = Mathf.Clamp(count, 1, 10);
  33. }
  34. for (int i = 0; i < count; i++)
  35. {
  36. StartCoroutine(RandomSound());
  37. }
  38. }
  39. public IEnumerator RandomSound()
  40. {
  41. float wait = Random.Range(0.5f, 4.5f);
  42. yield return new WaitForSeconds(wait);
  43. AudioClip clip = audioSources[Random.Range(0, audioSources.Length)];
  44. float volume = Random.Range(volumes[0], volumes[1]);
  45. PlayClipAt(clip, Vector3.zero, (!mute) ? volume : 0);
  46. if (makeSolo)
  47. {
  48. foreach (AudioRandomiser audioRandomiser in FindObjectsOfType<AudioRandomiser>())
  49. if (audioRandomiser != this)
  50. audioRandomiser.mute = true;
  51. GetComponent<AudioSource>().volume /= 2f;
  52. yield return new WaitForSeconds(clip.length);
  53. GetComponent<AudioSource>().volume *= 2f;
  54. foreach (AudioRandomiser audioRandomiser in FindObjectsOfType<AudioRandomiser>())
  55. if (audioRandomiser != this)
  56. audioRandomiser.mute = false;
  57. }
  58. }
  59. public IEnumerator PlayClips()
  60. {
  61. yield return new WaitForSeconds(waitTime);
  62. PlaySoundFromCount();
  63. StartCoroutine(PlayClips());
  64. }
  65. AudioSource PlayClipAt(AudioClip clip, Vector3 pos, float volume)
  66. {
  67. GameObject tempGO = new GameObject("TempAudio"); // create the temp object
  68. tempGO.transform.position = pos; // set its position
  69. AudioSource aSource = tempGO.AddComponent<AudioSource>(); // add an audio source
  70. aSource.clip = clip; // define the clip
  71. // set other aSource properties here, if desired
  72. aSource.volume = volume;
  73. aSource.spatialBlend = spacialBlend;
  74. aSource.Play(); // start the sound
  75. Destroy(tempGO, clip.length); // destroy object after clip duration
  76. return aSource; // return the AudioSource reference
  77. }
  78. }