From cbfceab8acd081afba3a5dbe5a23850160ef605c Mon Sep 17 00:00:00 2001 From: HungDK <> Date: Wed, 29 Oct 2025 17:02:43 +0700 Subject: [PATCH] Add sfx login --- Assets/PerfectWorld/Scripts/Sound.meta | 8 +++ .../Scripts/Sound/AudioManager.cs | 58 +++++++++++++++++++ .../Scripts/Sound/AudioManager.cs.meta | 2 + 3 files changed, 68 insertions(+) create mode 100644 Assets/PerfectWorld/Scripts/Sound.meta create mode 100644 Assets/PerfectWorld/Scripts/Sound/AudioManager.cs create mode 100644 Assets/PerfectWorld/Scripts/Sound/AudioManager.cs.meta diff --git a/Assets/PerfectWorld/Scripts/Sound.meta b/Assets/PerfectWorld/Scripts/Sound.meta new file mode 100644 index 0000000000..b97db3ed25 --- /dev/null +++ b/Assets/PerfectWorld/Scripts/Sound.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: eca6878d79ebfcf419afac70ed533edd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/PerfectWorld/Scripts/Sound/AudioManager.cs b/Assets/PerfectWorld/Scripts/Sound/AudioManager.cs new file mode 100644 index 0000000000..af0ec4413d --- /dev/null +++ b/Assets/PerfectWorld/Scripts/Sound/AudioManager.cs @@ -0,0 +1,58 @@ +using System.Collections; +using UnityEngine; + +public class AudioManager : MonoBehaviour +{ + public static AudioManager Instance; + public AudioSource bgmSource; + + void Awake() + { + if (Instance == null) + { + Instance = this; + DontDestroyOnLoad(gameObject); + } + else Destroy(gameObject); + } + + public void PlayBGM(AudioClip clip, float fadeTime = 1f) + { + StartCoroutine(FadeInBGM(clip, fadeTime)); + } + public void StopBGM(float fadeTime = 1f) + { + StartCoroutine(FadeOut(fadeTime)); + } + + + IEnumerator FadeInBGM(AudioClip clip, float fadeTime) + { + if (bgmSource.isPlaying) + yield return StartCoroutine(FadeOut(fadeTime)); + + bgmSource.clip = clip; + bgmSource.Play(); + + float t = 0f; + while (t < fadeTime) + { + t += Time.deltaTime; + bgmSource.volume = Mathf.Lerp(0, 1, t / fadeTime); + yield return null; + } + } + + IEnumerator FadeOut(float fadeTime) + { + float startVol = bgmSource.volume; + float t = 0f; + while (t < fadeTime) + { + t += Time.deltaTime; + bgmSource.volume = Mathf.Lerp(startVol, 0, t / fadeTime); + yield return null; + } + bgmSource.Stop(); + } +} \ No newline at end of file diff --git a/Assets/PerfectWorld/Scripts/Sound/AudioManager.cs.meta b/Assets/PerfectWorld/Scripts/Sound/AudioManager.cs.meta new file mode 100644 index 0000000000..b919750c5b --- /dev/null +++ b/Assets/PerfectWorld/Scripts/Sound/AudioManager.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ab7ebb437fbd3fb41a7300a381fcab00 \ No newline at end of file