[유니티]탑다운 슈팅 따라하기 #23 오디오 Part2

안녕하세요 유랑입니다.

 

 

실력향상을 위해서 오늘은 유튜브를 따라하면서 공부하겠습니다.

궁금하신점 있으시다면 댓글로 남겨주세요^^

 

 

 

1. 탑다운 슈팅 따라하기

 

 

이번 강의는 Sebastian Lague님께서 만든 예제이며,

유튜브를 보시면 자세한 내용을 배우실 수 있습니다.

 

유튜브 사이트 => 유튜브 

 

 

 

유니티 슈팅

 

 

 

1. 오디오

 

 

이번 시간에는 오디오를 적용해보겠습니다.

적의 공격, 사망, 플레이어에게도 필요하겠죠?

지난 시간에 이어서 오디오를 다뤄보겠습니다.

 

 

 

유니티 슈팅

 

 

 

2-1) 스크립트 작성 -SoundLibrary

 

 

SoundLibrary는 비슷한 내용의 사운드를 그룹화 시켜

랜덤하게 실행시켜 주는 역할을 합니다.

 

 

 

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

// 사운드 그룹화
public class SoundLibrary : MonoBehaviour
{
    public SoundGroup[] soundGroups;

    Dictionary<string, AudioClip[]> groupDictionary = new Dictionary<string, AudioClip[]>();

    void Awake()
    {
        foreach (SoundGroup soundGroup in soundGroups)
        {
            groupDictionary.Add(soundGroup.groupID, soundGroup.group);
        }
    }
    // 해당 이름의 랜덤 사운드를 반환
    public AudioClip GetClipFromName(string name)
    {
        if (groupDictionary.ContainsKey(name))
        {
            AudioClip[] sounds = groupDictionary[name];
            return sounds[Random.Range(0, sounds.Length)];
        }
        return null;
    }

    [System.Serializable]
    public class SoundGroup
    {
        public string groupID;
        public AudioClip[] group;
    }
}

 

 

 

2-2) 스크립트 작성 -㉡AudioManager

 

 

AudioManager 스크립트에는 사운드 볼륨값을 PlayerPrefs를 통해

따로 저장해 줍니다.

이제 게임 실행이 끝나도 저장이 가능하니 걱정없겠네요^^

 

 

 

using UnityEngine;
using System.Collections;

public class AudioManager : MonoBehaviour
{
    public enum AudioChannel { Master, Sfx, Music };

    float masterVolumePercent = 0.2f; // 마스터 볼륨
    float sfxVolumePercent = 1;       // 사운드 효과 볼륨
    float musicVolumePercent = 1f;    // 음악 볼륨

    AudioSource sfx2DSource;
    AudioSource[] musicSources;
    int activeMusicSourceIndex;

    public static AudioManager instance; // 싱글턴

    Transform audioListener;
    Transform playerT;

    SoundLibrary library;

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

            library = GetComponent<SoundLibrary>();

            musicSources = new AudioSource[2];
            for (int i = 0; i < 2; i++)
            {
                GameObject newMusicSource = new GameObject("Music source " + (i + 1));
                musicSources[i] = newMusicSource.AddComponent<AudioSource>();
                newMusicSource.transform.parent = transform;
            }
            GameObject newSfx2Dsource = new GameObject("2D sfx source");
            sfx2DSource = newSfx2Dsource.AddComponent<AudioSource>();
            newSfx2Dsource.transform.parent = transform;

            audioListener = FindObjectOfType<AudioListener>().transform;
            playerT = FindObjectOfType<Player>().transform;

            masterVolumePercent = PlayerPrefs.GetFloat("master vol", masterVolumePercent);
            sfxVolumePercent = PlayerPrefs.GetFloat("sfx vol", sfxVolumePercent);
            musicVolumePercent = PlayerPrefs.GetFloat("music vol", musicVolumePercent);
        }
    }

    void Update()
    {
        if (playerT != null)
        {
            audioListener.position = playerT.position;
        }
    }
    // 사운드 볼륨 설정
    public void SetVolume(float volumePercent, AudioChannel channel)
    {
        switch (channel)
        {
            case AudioChannel.Master:
                masterVolumePercent = volumePercent;
                break;
            case AudioChannel.Sfx:
                sfxVolumePercent = volumePercent;
                break;
            case AudioChannel.Music:
                musicVolumePercent = volumePercent;
                break;
        }

        musicSources[0].volume = musicVolumePercent * masterVolumePercent;
        musicSources[1].volume = musicVolumePercent * masterVolumePercent;

        PlayerPrefs.SetFloat("master vol", masterVolumePercent);
        PlayerPrefs.SetFloat("sfx vol", sfxVolumePercent);
        PlayerPrefs.SetFloat("music vol", musicVolumePercent);
    }

    public void PlayMusic(AudioClip clip, float fadeDuration = 1)
    {
        activeMusicSourceIndex = 1 - activeMusicSourceIndex;
        musicSources[activeMusicSourceIndex].clip = clip;
        musicSources[activeMusicSourceIndex].Play();

        StartCoroutine(AnimateMusicCrossfade(fadeDuration));
    }
    // 사운드 재생
    public void PlaySound(AudioClip clip, Vector3 pos)
    {
        if (clip != null)
        {
            // 정해진 위치에서 클립 발생
            AudioSource.PlayClipAtPoint(clip, pos, sfxVolumePercent * masterVolumePercent);
        }
    }
    public void PlaySound(string soundName, Vector3 pos)
    {
        PlaySound(library.GetClipFromName(soundName), pos);
    }

    public void PlaySound2D(string soundName)
    {
        sfx2DSource.PlayOneShot(library.GetClipFromName(soundName), sfxVolumePercent * masterVolumePercent);
    }
    // 음악 크로스페이드
    IEnumerator AnimateMusicCrossfade(float duration)
    {
        float percent = 0;

        while (percent < 1)
        {
            percent += Time.deltaTime * 1 / duration;
            musicSources[activeMusicSourceIndex].volume = Mathf.Lerp(0, musicVolumePercent * masterVolumePercent, percent);
            musicSources[1 - activeMusicSourceIndex].volume = Mathf.Lerp(musicVolumePercent * masterVolumePercent, 0, percent);
            yield return null;
        }
    }
}

 

 

 

2-3) 스크립트 작성 -㉢Enemy

 

 

Enemy 스크립트에 적의 사망과 어택에 대한 사운드 내용을 추가해 주겠습니다.

 

 

 

유니티 슈팅

 

 

 

2-4) 스크립트 작성 -㉣Spawner

 

 

Spawner 스크립트에는 다음 웨이브로 넘어갈 때 마다

스테이지 클리어를 했다는 사운드를 추가해 주겠습니다.

 

 

 

유니티 슈팅

 

 

 

2-5) 스크립트 작성 -㉤LivingEntity

 

 

LivingEntity Die를 상속받을 수 있도록 변경해 줍니다.

이제 Player 스크립트에서 Die에 사운드 내용을 추가해 줄 수 있습니다.

 

 

 

유니티 슈팅

 

 

 

2-6) 스크립트 작성 -㉥Player

 

 

Player 스크립트에 override를 이용해 사운드 내용을 덮어씌어주겠습니다.

 

 

 

유니티 슈팅

 

 

 

2-7) 스크립트 적용

 

 

사운드 그룹에 해당 사운드를 적용시켜 주세요.

적 죽음부터 플레이어 죽음까지 다양한 사운드 그룹이 존재합니다.

 

 

 

유니티 슈팅

 

 

 

 

 

3. 마무리

 

 

오늘 강의는 여기까지입니다.

탑다운 슈팅을 따라하면서 오디오를 적용해 보았습니다.

감사합니다.

 

 

 

수업자료: 탑다운 슈팅 따라하기 #23 오디오 Part2

 

 

 

 

 

 

댓글

Designed by JB FACTORY