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)의 갯수만큼 반복문을 돌려

 

씬 이름과 배열에 등록된 음악의 인덱스 번호가 동일하면

 

if문 실행, 그렇지 않을 경우 debug.log

 

PlayBackgroundSound 메서드에 배열에 등록된 음악 실행

 

처음에 음악이 실행되지 않아

 

Debug.Log로 backgroundMusicList.Length를 찍었으나 정상적으로 나왔고

 

이후 Debug.Log로 scene.name == backgroundMusicLists[i].name이 맞는지

 

확인했는데 false가 나왔다. 음악파일명과 씬 이름이 달라서 실행되지 않은 문제

 

public void PlayBackgroundSound(AudioClip clip)
{
    backgroundMusic.clip = clip;
    backgroundMusic.loop = true;
    backgroundMusic.volume = 1f;
    backgroundMusic.Play();
}

 

PlayBackgroundSound

Audiosource에 Audioclip을 매개변수로 넘겨주고 

반복해서 실행할 수 있도록 loop를 true로 설정

 

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);
}

 

PlaySfxSound

 

게임오브젝트를 생성하고

 

생성된 객체에 AudioSoucre 메서드를 추가(AddComponent) 해준다.

 

이후 음악이 종료되면 파괴(종료)

 

다른곳에서 실행할 경우

 

public AudioClip clip;

AudioManager.Instance.PlaySfxSound("실행할 음악 이름", clip)

 

이때 clip에 bgm을 할당해야한다.

 

 

 

+ Recent posts