[Unity] Road to Picnic (Craft_Week) - Sound

박호준·2022년 5월 30일
0

Craft_Week

목록 보기
19/20
post-thumbnail

Sound 넣기

Singleton patteron으로 soundcontroller 만들기

private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(instance);
        }
        else
            Destroy(gameObject);
    }

Scene이 변경될 때 자동으로 background sound 재생시키기

public class SoundController : MonoBehaviour
{

    public static SoundController instance;
    public AudioSource bgSound;
    public AudioClip[] bglist;
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(instance);
            SceneManager.sceneLoaded += OnSceneLoad; //Scene이 변경될때 실행하기
        }
        else
            Destroy(gameObject);
    }

    private void OnSceneLoad(Scene arg0, LoadSceneMode arg1)
    {
        for (int i = 0; i < bglist.Length; ++i)
        {
            if (arg0.name == bglist[i].name) {
                BgSoundPlay(bglist[i]);
                break ;
            }
        }
    }

}

효과음 넣기

    public void SFXPlay(string sfxName, AudioClip clip)
    {
        GameObject sound = new GameObject(sfxName + "sound");
        AudioSource audioSource = sound.AddComponent<AudioSource>();
        audioSource.clip = clip;
        audioSource.Play();
        if (sound)
            Destroy(sound, clip.length);
    }
profile
hopark

0개의 댓글