using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class AudioManager : MonoBehaviour
{
public static AudioManager instance;
public AudioSource backgroundMusic;
public AudioClip[] backgroundMusicLists;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
SceneManager.sceneLoaded += OnSceneLoaded;
}
else
{
Destroy(gameObject);
}
backgroundMusic = GetComponent<AudioSource>();
}
private void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
{
for (int i = 0; i < backgroundMusicLists.Length; i++)
{
if (scene.name == backgroundMusicLists[i].name)
{
PlayBackgroundSound(backgroundMusicLists[i]);
}
else
{
Debug.Log("씬 이름이 맞지 않거나 해당씬에 맞는 bgm 할당이 되지 않았습니다.");
}
}
}
public void PlaySfxSound(string sfxName, AudioClip clip)
{
GameObject audio = new GameObject(sfxName + "Sound");
AudioSource audioSource = audio.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Destroy(audio, clip.length);
}
public void PlayBackgroundSound(AudioClip clip)
{
backgroundMusic.clip = clip;
backgroundMusic.loop = true;
backgroundMusic.volume = 1f;
backgroundMusic.Play();
}
}
사운드를 담당하는 사운드 매니저
public static AudioManager instance;
public AudioSource backgroundMusic;
public AudioClip[] backgroundMusicLists;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
SceneManager.sceneLoaded += OnSceneLoaded;
}
else
{
Destroy(gameObject);
}
}
다른 클래스에서 접근할 수 있게 싱글톤으로 만들고
씬이 로드할때 구독된 OnSceneLoaded 메서드 호출
private void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
{
for (int i = 0; i < backgroundMusicLists.Length; i++)
{
if (scene.name == backgroundMusicLists[i].name)
{
PlayBackgroundSound(backgroundMusicLists[i]);
}
else
{
Debug.Log("씬 이름이 맞지 않거나 해당씬에 맞는 bgm 할당이 되지 않았습니다.");
}
}
}
OnSceneLoaded
Audioclip 배열(backgroundMusicList.Length)의 갯수만큼 반복문을 돌려