[Unity] How to add background music switch button

Time:2022-11-16

illustrate

I thought of this method by clicking the button to complete the scene switching process (I found a lot of information on the Internet before, but I didn’t understand it because of my lack of level, so I had to explore it myself). Just move the button’sOn Clickwith the control music scriptGameObjectIt can be achieved by linking. Switching the scene is just a method defined in the script to load the scene, changing to other methods can achieve many things.

step

Step 1: Add the UI of the music button. (Add Button)
Step Two: Create aGameObject(I named it GameManagerMusic), and inside it addAudio Sourceand aScriptscript component. Drag the file as background music into AudioClip, and check Play On Awake and Loop (loop playback).
Script is used to control the switch judgment of music:

private AudioSource audio;//Definition of sound components
public AudioClip Music;//place music    


void Start()
{
    audio = this. GetComponent<AudioSource> ();//Get the sound component
}

//Click trigger to turn on/off background music
public void OnMusicControl()
{
    audio.clip = Music;
    if (audio.isPlaying == false)
    {
        audio.Play();
    }
    else
    {
        audio.Stop();
    }
}

Step 3: InButtoncomponentOn Click()Click the “+” sign in the item, and put the created in the second stepGameObjectDrag the component into it, select the created Script script in the drop-down box on the right, and select the created method in itOnMusicControl()That’s it.