Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class SoundFXHandler : MonoBehaviour
- {
- public int maxSources = 25;
- public SoundFX[] sounds;
- private List<AudioSource> audioSources = new List<AudioSource>();
- private static SoundFXHandler _instance;
- public static SoundFXHandler Instance { get { return _instance; } }
- private void Awake()
- {
- if (_instance != null && _instance != this)
- Destroy(gameObject);
- else
- _instance = this;
- }
- public void PlaySound (string fxName, Vector3 location)
- {
- AudioSource audioSource = GetAudioSource();
- if (audioSource == null)
- return;
- foreach (SoundFX soundFX in sounds)
- {
- if (fxName == soundFX.name)
- {
- audioSource.transform.position = location;
- soundFX.Attach(audioSource);
- return;
- }
- }
- Debug.LogWarning("Could not find SoundFX, \"" + fxName + " \" in sounds array");
- }
- public AudioSource PlaySoundRaw(AudioClip clip, Vector3 location)
- {
- AudioSource audioSource = GetAudioSource();
- if (audioSource == null)
- return null;
- audioSource.transform.position = location;
- audioSource.spatialBlend = 1f;
- audioSource.clip = clip;
- audioSource.Play();
- return audioSource;
- }
- public void PlaySound2DRaw(AudioClip clip)
- {
- AudioSource audioSource = GetAudioSource();
- if (audioSource == null)
- return;
- audioSource.spatialBlend = 0f;
- audioSource.clip = clip;
- audioSource.Play();
- }
- public AudioSource GetSound2DRaw(AudioClip clip)
- {
- AudioSource audioSource = GetAudioSource();
- if (audioSource == null)
- return null;
- audioSource.name = clip.name;
- audioSource.spatialBlend = 0f;
- audioSource.clip = clip;
- return audioSource;
- }
- private AudioSource GetAudioSource ()
- {
- // foreach (AudioSource source in audioSources)
- // {
- // if (!source.isPlaying)
- // return source;
- // }
- if (audioSources.Count < maxSources)
- {
- GameObject newAudioSource = new GameObject();
- newAudioSource.transform.SetParent(transform);
- audioSources.Add(newAudioSource.AddComponent<AudioSource>());
- return audioSources[audioSources.Count - 1];
- }
- Debug.LogWarning("No available audio sources found and maximum number of audio sources reached.");
- return null;
- }
- }
- [System.Serializable]
- public class SoundFX
- {
- #region Initialise Variables
- [Header("FX Details")]
- public string name = "New Sound";
- public AudioClip clip = null;
- [Header("FX Settings")]
- public bool loop = false;
- [Range(0f, 1f)]
- public float volume = 1f;
- #endregion
- public SoundFX (AudioClip _clip)
- {
- clip = _clip;
- }
- public SoundFX (string _name, AudioClip _clip)
- {
- name = _name;
- clip = _clip;
- }
- public void Attach (AudioSource audioSource)
- {
- audioSource.clip = clip;
- audioSource.loop = loop;
- audioSource.volume = volume;
- audioSource.spatialBlend = 1f;
- audioSource.Play();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment