Coding Feature.

[Unity 3D] 3D 퐁 만들기 #5 Audio Manager 구현, 효과음, 배경 음악 설정 본문

Toy Project/MICRO-PONG [Unity3D]

[Unity 3D] 3D 퐁 만들기 #5 Audio Manager 구현, 효과음, 배경 음악 설정

codingfeature 2024. 1. 20. 00:38

이제 Audio Manager를 만들어서 배경음악과 효과음을 구현해보겠습니다.

 

유니티 Sound 관련해서는 제가 많이 부족해서 아래 유튜브를 참고해서 간단한 Audio Manager 스크립트를 만들었습니다.

굉장히 유용한 영상이니 궁금하시면 참고 부탁드릴게요!

 

https://youtu.be/6OT43pvUyfY?si=wpQEfza1ZcVOscyW

 

먼저 Sound 클래스를 스크립트로 작성해서 각 음성의 속성을 정의했습니다.

 

using UnityEngine.Audio;
using UnityEngine;

[System.Serializable]
public class Sound
{
    public string name;

    public AudioClip clip;

    [Range(0f, 1f)]
    public float volume;
    [Range(.1f, 3f)]
    public float pitch;

    public bool loop;

    [HideInInspector]
    public AudioSource source;
}

 

Sound 객체는 이름, AudioClip, 볼륨, pitch, looping 유무, 그리고 AudioSource 값을 가지게 됩니다.

AudioClip은 음성 파일을 담고 AudioSource 컴포넌트를 통해 볼륨, 피치 등이 알맞게 조절되며 소리가 나오게 됩니다.

 

그리고 아래는 Audio Manager 스크립트입니다.

 

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

public class AudioManager : MonoBehaviour
{
    private static AudioManager instance;
    public Sound[] sounds;
    public static AudioManager Instance
    {
        get
        {
            return instance;
        }
    }
    private void Awake()
    {
        if (instance)
        {
            Destroy(instance);
            return;
        }

        instance = this;
        DontDestroyOnLoad(this.gameObject);

        foreach(Sound s in sounds) // 각 sound 객체의 AudioSource 컴포넌트 생성 및 여러 세팅.
        {
            s.source = gameObject.AddComponent<AudioSource>();
            s.source.clip = s.clip;
            s.source.volume = s.volume;
            s.source.pitch = s.pitch;
            s.source.loop = s.loop;
        }
    }
    
    public void Play(string name)
    {
        Sound s = Array.Find(sounds, sound => sound.name == name); // sounds 배열 내 name과 같은 이름을 가진 sound 찾기.

        if(s == null) // sound를 찾지 못한 경우,
        {
            Debug.LogWarning("Sound : " + name + " Not Found!");
            return;
        }
        s.source.Play();
    }

}

 

위 Sound 클래스의 각 객체를 배열 형태로 sounds에 저장하고,

awake일때 각 sound에 대해서 AudioSource 컴포넌트를 만들고 미리 설정된 clip, volume, pitch, loop 여부 를 컴포넌트에 설정하게 됩니다.

 

그리고 Play 함수를 통해서 name을 입력받고 그 name과 동일한 sound 객체를 찾은 경우 AudioSource를 통해 소리를 재생하게 됩니다.

 

 

그리고 Audio Manager의 Inspector에서 다음과 같이 설정해주고,

 

각 효과음 또는 음악이 발생하는 코드에 Play 함수를 넣습니다.

 

예를 들어 점수가 1씩 오를 때의 sound인 Score는 다음과 같이 구현합니다.

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ball")) // 플레이어가 공에 닿을 경우,
        {
            GameManager.Instance.score += 1;

            ball.GetComponent<BallScript>().AddBallSpeed(GameManager.Instance.ballSpeedIncrement);
            ball.GetComponent<BallScript>().RotateBallVector(Random.Range(0f, 360f));
            StartCoroutine(UIManager.Instance.ShowScore());

            AudioManager.Instance.Play("Score"); // Score 소리 재생
        }
    }

 

 

효과음과 배경 음악의 원작자는 다음과 같습니다.

Abstraction - http://www.abstractionmusic.com/

"Sound Effects by Coffee 'Valen' Bat"

 

 

다음은 게임의 텍스쳐와 이펙트를 네온 테마에 맞게 바꾸어 보도록 하겠습니다!