53 lines
1.4 KiB
C#
53 lines
1.4 KiB
C#
|
|
using UnityEngine;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
|
||
|
|
public class AudioPool : MonoBehaviour
|
||
|
|
{
|
||
|
|
public static AudioPool Instance;
|
||
|
|
|
||
|
|
[Header("Settings")]
|
||
|
|
public int poolSize = 15;
|
||
|
|
private List<AudioSource> pool = new List<AudioSource>();
|
||
|
|
|
||
|
|
void Awake()
|
||
|
|
{
|
||
|
|
if (Instance == null)
|
||
|
|
{
|
||
|
|
Instance = this;
|
||
|
|
DontDestroyOnLoad(gameObject);
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
Destroy(gameObject);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Khởi tạo pool các AudioSource
|
||
|
|
for (int i = 0; i < poolSize; i++)
|
||
|
|
{
|
||
|
|
AudioSource source = gameObject.AddComponent<AudioSource>();
|
||
|
|
source.playOnAwake = false;
|
||
|
|
pool.Add(source);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public void PlaySound(AudioClip clip, float volume = 1f, bool randomizePitch = false)
|
||
|
|
{
|
||
|
|
if (clip == null) return;
|
||
|
|
|
||
|
|
// Tìm AudioSource đang rảnh
|
||
|
|
AudioSource source = pool.Find(s => !s.isPlaying);
|
||
|
|
|
||
|
|
// Nếu tất cả đều đang bận, dùng đại cái đầu tiên
|
||
|
|
if (source == null) source = pool[0];
|
||
|
|
|
||
|
|
source.clip = clip;
|
||
|
|
source.volume = volume;
|
||
|
|
|
||
|
|
// Thêm một chút biến tấu cao độ để âm thanh tự nhiên hơn (không bị máy móc)
|
||
|
|
source.pitch = randomizePitch ? Random.Range(0.9f, 1.1f) : 1f;
|
||
|
|
|
||
|
|
source.Play();
|
||
|
|
}
|
||
|
|
}
|