Reviewed-on: #1 Co-authored-by: Jeremy Smitherman <Jeremysmitherman@gmail.com> Co-committed-by: Jeremy Smitherman <Jeremysmitherman@gmail.com>
50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace Management
|
|
{
|
|
[RequireComponent(typeof(AudioSource))]
|
|
public class SFX : MonoBehaviour
|
|
{
|
|
[SerializeField] private int maxActiveClips;
|
|
|
|
private static SFX _instance;
|
|
private AudioSource _audioSource;
|
|
private Dictionary<AudioClip, int> _clipsInProgress;
|
|
|
|
public void PlayOneShot(AudioClip clip, float volume = 1f)
|
|
{
|
|
if (clip == null) return;
|
|
if (!_clipsInProgress.TryAdd(clip, 1))
|
|
{
|
|
if (_clipsInProgress[clip] >= maxActiveClips) return;
|
|
_clipsInProgress[clip]++;
|
|
}
|
|
|
|
_audioSource.PlayOneShot(clip, volume);
|
|
StartCoroutine(ClearClip(clip));
|
|
}
|
|
|
|
private IEnumerator ClearClip(AudioClip clip)
|
|
{
|
|
yield return new WaitForSeconds(clip.length);
|
|
_clipsInProgress[clip]--;
|
|
if (_clipsInProgress[clip] <= 0) _clipsInProgress.Remove(clip);
|
|
}
|
|
|
|
private void Awake()
|
|
{
|
|
if (_instance != null && _instance != this)
|
|
{
|
|
Destroy(gameObject);
|
|
return;
|
|
}
|
|
|
|
_instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
_audioSource = GetComponent<AudioSource>();
|
|
}
|
|
}
|
|
}
|