Published on

(Unity) Play Background Music and SE - Using AudioSource

Authors
  • Evelyn

Please share this article if you like!

Hi! This article explains how to handle sound in Unity.

I'll miss the music in games. I want to hear the sound effects of the characters' actions.

Please read to the end as it will satisfy your needs.

Table of Contents

How sound is handled in Unity

In unity

  • Audio Source : the source of the sound
  • Audio Listener : the place to listen to the sound.

which is the place to listen to the sound, you will be able to play the sound.

In the case of 3D, it seems to be possible to make the audio sound quieter if the Audio Listener and Audio Source are far away from each other; in the case of 2D, it doesn't matter, but you need both.

Play background music

  1. Add an AudioSource component to any game object.
  2. Add background music to AudioClip.
  3. Activate the Loop checkbox to make the background music loop.

Play an SE when a button is clicked

Finally, we will play a sound effect when the button is clicked.

First, let's create the following C Sharp script.

AudioButton.cs

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

[RequireComponent(typeof(AudioSource))]
public class AudioButton : MonoBehaviour
{
    public AudioClip thisAudioClip;
    private AudioSource AudioSource;

    void Start()
    {
        AudioSource = GetComponent<AudioSource>();
    }

    public void OnClick()
    {
        AudioSource.PlayOneShot(thisAudioClip);
    }
}

Next, we will add a script for the button.

In addition, assign an AudioClip to the This Audio Clip variable, and assign the script's OnClick method to the button's OnClick event

When executed, a sound will be played when the button is clicked.

Summary of this article

This is how to play background music and sounds in Unity.

How to play sound in Unity
  • Need Audio Listener and AudioSource
  • Use the PlayOneShot method to play the SE.

I'd be happy if your game incorporates background music and sound effects to inspire players.

Thank you for reading to the end. If you like this blog, please help me by subscribing to it on Feedly or referring me to your friends.

Please share this article if you like!