|
|
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using JetBrains.Annotations;
- using UnityEngine;
- using Random = UnityEngine.Random;
-
- public class AudioRandomiser : MonoBehaviour
- {
- public AudioClip[] audioSources;
- public HerdController herd;
-
- public GameObject audioPosition;
- public float waitTime;
- public float[] volumes;
-
- public bool makeSolo;
- public bool mute;
-
- [Range(0, 1)]
- public float spacialBlend = 1;
-
- // Start is called before the first frame update
- void Start()
- {
-
- }
-
- void Awake()
- {
- StartCoroutine(PlayClips());
- }
-
- public void PlaySoundFromCount()
- {
- int count = 1;
- if (herd != null)
- {
- count = (int)Mathf.Round(herd.HerdAmount() / 10);
- count = Mathf.Clamp(count, 1, 10);
- }
-
- for (int i = 0; i < count; i++)
- {
- StartCoroutine(RandomSound());
- }
- }
-
-
- public IEnumerator RandomSound()
- {
- float wait = Random.Range(0.5f, 4.5f);
- yield return new WaitForSeconds(wait);
- AudioClip clip = audioSources[Random.Range(0, audioSources.Length)];
- float volume = Random.Range(volumes[0], volumes[1]);
- PlayClipAt(clip, Vector3.zero, (!mute) ? volume : 0);
- if (makeSolo)
- {
- foreach (AudioRandomiser audioRandomiser in FindObjectsOfType<AudioRandomiser>())
- if (audioRandomiser != this)
- audioRandomiser.mute = true;
-
- GetComponent<AudioSource>().volume /= 2f;
- yield return new WaitForSeconds(clip.length);
- GetComponent<AudioSource>().volume *= 2f;
-
- foreach (AudioRandomiser audioRandomiser in FindObjectsOfType<AudioRandomiser>())
- if (audioRandomiser != this)
- audioRandomiser.mute = false;
- }
- }
-
- public IEnumerator PlayClips()
- {
- yield return new WaitForSeconds(waitTime);
- PlaySoundFromCount();
-
- StartCoroutine(PlayClips());
- }
-
- AudioSource PlayClipAt(AudioClip clip, Vector3 pos, float volume)
- {
- GameObject tempGO = new GameObject("TempAudio"); // create the temp object
- tempGO.transform.position = pos; // set its position
- AudioSource aSource = tempGO.AddComponent<AudioSource>(); // add an audio source
- aSource.clip = clip; // define the clip
- // set other aSource properties here, if desired
-
- aSource.volume = volume;
- aSource.spatialBlend = spacialBlend;
- aSource.Play(); // start the sound
- Destroy(tempGO, clip.length); // destroy object after clip duration
- return aSource; // return the AudioSource reference
- }
-
-
- }
|