[패스트캠퍼스 수강 후기] 올인원 패키지 : 유니티 포트폴리오 완성 100% 환급 챌린지 38회차 미션 시작합니다.

04. 배틀로얄 - 21, 22 번을 진행합니다.




저번 시간에 이어 SoundManager 스크립트를 지속 작업합니다.

public class SoundManager : SingletonMonobehaviour<SoundManager>
{
    // 저번시간 작성했던 변수들..
    
    void Start() {
        if (mixer == null) {
            mixer = Resources.Load(MixerName) as AudioMixer;
        }
        if (audioRoot == null) {
            audioRoot = new GameObject(ContainerName).transform;
            audioRoot.SetParent(transform);
            audioRoot.localPosition = Vector3.zero;
        }
        if (fadeA_audio == null) {
            GameObject fadeA = new GameObject(FadeA, typeof(AudioSource));
            fadeA.transform.SetParent(audioRoot);
            fadeA_audio = fadeA.GetComponent<AudioSource>();
            fadeA_audio.playOnAwake = false;
        }
        if (fadeB_audio == null) {
            GameObject fadeB = new GameObject(FadeB, typeof(AudioSource));
            fadeB.transform.SetParent(audioRoot);
            fadeB_audio = fadeB.GetComponent<AudioSource>();
            fadeB_audio.playOnAwake = false;
        }
        if (UI_audio == null) {
            GameObject ui = new GameObject(UI, typeof(AudioSource));
            ui.transform.SetParent(audioRoot);
            UI_audio = ui.GetComponent<AudioSource>();
            UI_audio.playOnAwake = false;
        }
        if (effect_audios == null || effect_audios.Length == 0) {
            effect_PlayStartTime = new float[EffectChannelCount];
            effect_audios = new AudioSource[EffectChannelCount];
            for (int i = 0; i < EffectChannelCount; i++) {
                effect_PlayStartTime[i] = 0.0f;
                GameObject effect = new GameObject("Effect" + i.ToString(), typeof(AudioSource));
                effect.transform.SetParent(audioRoot);
                effect_audios[i] = effect.GetComponent<AudioSource>();
                effect_audios[i].playOnAwake = false;
            }
        }
        
        if (mixer != null) {
            fadeA_audio.outputAudioMixerGroup = mixer.FindMatchingGroups(BGMGroupName)[0];
            fadeA_audio.outputAudioMixerGroup = mixer.FindMatchingGroups(BGMGroupName)[0];
            UI_audio.outputAudioMixerGroup = mixer.FindMatchingGroups(UIGroupName)[0];
            for (int i = 0; i < effect_audios.Length; i++) {
                effect_audios[i].outputAudioMixerGroup = mixer.FindMatchingGroups(EffectGroupName)[0];
            }
        }
        
        VolumeInit();
    }
    
    public void SetBGMVolume(float currentRatio) {
        currentRatio = Mathf.Clamp01(currentRatio);
        float volume = Mathf.Lerp(minVolume, maxVolume, currentRatio);
        mixer.SetFloat(BGMVolumeParam, volume);
        PlayerPrefs.SetFloat(BGMVolumeParam, volume);
    }
    
    public float GetBGMVolume() {
        if (PlayerPrefs.HasKey(BGMVolumeParam))
            return Mathf.Lerp(minVolume, maxVolume, PlayerPrefs.GetFloat(BGMVolumeParam));
        else
            return maxVolume;
    }
    
    public void SetEffectVolume(float currentRatio) {
        currentRatio = Mathf.Clamp01(currentRatio);
        float volume = Mathf.Lerp(minVolume, maxVolume, currentRatio);
        mixer.SetFloat(EffectVolumeParam, volume);
        PlayerPrefs.SetFloat(EffectVolumeParam, volume);
    }
    
    public float GetEffectVolume() {
        if (PlayerPrefs.HasKey(EffectVolumeParam))
            return Mathf.Lerp(minVolume, maxVolume, PlayerPrefs.GetFloat(EffectVolumeParam));
        else
            return maxVolume;
    }
    
    public void SetUIVolume(float currentRatio) {
        currentRatio = Mathf.Clamp01(currentRatio);
        float volume = Mathf.Lerp(minVolume, maxVolume, currentRatio);
        mixer.SetFloat(UIVolumeParam, volume);
        PlayerPrefs.SetFloat(UIVolumeParam, volume);
    }
    
    public float GetUIVolume() {
        if (PlayerPrefs.HasKey(UIVolumeParam))
            return Mathf.Lerp(minVolume, maxVolume, PlayerPrefs.GetFloat(UIVolumeParam));
        else
            return maxVolume;
    }
    

 



여기까지가 기본적인 사운드 초기화 및 초기 설정을 하는 코드입니다. 이어서 소리 켜고 끄기 및 Fade In/Out 등을 작성합니다.



    void PlayAudioSource(AudioSource source, SoundClip clip, float volume) {  // 소리 재생
        if (source == null || clip == null) return;
        source.Stop();
        source.clip = clip.GetClip();
        source.volume = volume;
        source.loop = clip.isLoop;
        source.pitch = clip.pitch;
        source.dopplerLevel = clip.dopplerLevel;
        source.rolloffMode = clip.rolloffMode;
        source.minDistance = clip.minDistance;
        source.maxDistance = clip.maxDistance;
        source.spartialBlend = clip.spartialBlend;
        source.Play();
    }
    
    void PlayAudioSourceAtPoint(SoundClip clip, Vector3 position, float volume) { // 특정 위치에서 재생
        AudioSource.PlayClipAtPoint(clip.GetClip(), position, volume);
    }
    
    public bool IsPlaying() {
        return (int)currentPlayingType > 0;
    }
    
    public bool IsDifferentSound(SoundClip clip) {
        if (clip == null) return false;
        if (currentSound != null && currentSound.realId == clip.realId && IsPlaying() && currentSound.isFadeOut == false) return false;
        else return true;
    }
   
    private IEnumerator CheckProcess() {
        while (isTicking == true && IsPlaying() == true) {
            yield return new WaitForSeconds(0.05f);
            if (currentSound.HasLoop()) {
                if (currentPlayingType == MusicPlayingType.SourceA) {
                    currentSound.CheckLoop(fadeA_audio);
                }
                else if (currentPlayingType == MusicPlayingType.SourceB) {
                    currentSound.CheckLoop(fadeB_audio);
                }
                else if (currentPlayingType == MusicPlayingType.AtoB) {
                    lastSound.CheckLoop(fadeA_audio);
                    currentSound.CheckLoop(fadeB_audio);
                }
                else if (currentPlayingType == MusicPlayingType.BtoA) {
                    lastSound.CheckLoop(fadeB_audio);
                    currentSound.CheckLoop(fadeA_audio);
                }
            }
        }
    }

 


DoCheck, FadeIn 함수도 위와 같이 구현해 줍니다.

    public void FadeIn(int index, float time, Interpolate.EaseType ease) {
        FadeIn(DataManager.SoundData().GetCopy(index), time, ease);
    }
    
    public void FadeOut(float time, Interpolate.EaseType ease) {
        if (currentSound != null)
            currentSound.FadeOut(time, ease);
    }
   
    void Update() {
        if (currentSound == null) return;
        if (currentPlayingType == MusicPlayingType.SourceA) {
            currentSound.DoFade(Time.deltaTime, fadeA_audio);
        }
        else if (currentPlayingType == MusicPlayingType.SourceB) {
            currentSound.DoFade(Time.deltaTime, fadeB_audio);
        }
        else if (currentPlayingType == MusicPlayingType.AtoB) {
            lastSound.DoFade(Time.deltaTime, fadeA_audio);
            currentSound.DoFade(Time.deltaTime, fadeB_audio);
        }
        else if (currentPlayingType == MusicPlayingType.BtoA) {
            lastSound.DoFade(Time.deltaTime, fadeB_audio);
            currentSound.DoFade(Time.deltaTime, fadeA_audio);
        }
        
        if (fadeA_audio.isPlaying && fadeB_audio.isPlaying == false) {
            currentPlayingType = MusicPlayingType.SourceA;
        }
        else if (fadeB_audio.isPlaying && fadeA_audio.isPlaying == false) {
            currentPlayingType = MusicPlayingType.SourceB;
        }
        else if (fadeA_audio.isPlaying == false && fadeB_audio.isPlaying == false) {
            currentPlayingType = MusicPlayingType.None;
        }
    }
}


사실 이런 구현은 말이 많을 것 같다는 느낌도 들긴 하네요. 분명 위와 같은 기능을 하는 툴이 있어야 함은 분명한데..
매번 툴을 만들때마다 많은 시간이 들어가야 하며 코드 관리도 힘들다면 오히려 짐이 될 것도 같기 때문입니다.

다음 시간에는 사운드 매니저를 마무리하고, 3인칭 카메라 제작에 들어갑니다 ^^~




<위의 코드들은 제가 보면서 주요한 함수, 코드를 확인하기 위해 타이핑한 용도로, 전체 소스코드가 아님에 주의해 주세요. 전체 코드는 교육 수강을 하면 완벽하게 받으실 수가 있답니다 ^^>

패스트캠퍼스 - 올인원 패키지 : 유니티 포트폴리오 완성 bit.ly/2R561g0

 

유니티 게임 포트폴리오 완성 올인원 패키지 Online. | 패스트캠퍼스

게임 콘텐츠 프로그래머로 취업하고 싶다면, 포트폴리오 완성은 필수! '디아블로'와 '배틀그라운드' 게임을 따라 만들어 보며, 프로그래머 면접에 나오는 핵심 개념까지 모두 잡아 보세요!

www.fastcampus.co.kr

 

+ Recent posts