Realize the control of background music volume

1. First in the Project level

Create an Audio folder: used to install the music we want

Then download the music you like and put it in this folder

2. Then in the Hierarchy

Right click to create UI: Canvas, Slider

The parent-child relationship is shown in the figure

 3. Write SliderMusic code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SliderMusic : MonoBehaviour
{
    private Slider musicSlider;
    void Start()
    {
        //找到层级中的物体
        //原式 Slider musicSlider = GameObject.Find("")
        //左边是Slider类型,右边是GameObject类型
        //所以要在后面添加GetComponent<Slider>();
        //负责解决省去 将层级里的对象,拖到脚本的Event中
        musicSlider = GameObject.Find("Canvas/Slider").GetComponent<Slider>();
        //原式 Slider.onValueChanged 是为了选择Event中哪个对象
        //添加AddListener中有两个参数(函数下,检查器组件的值value);
        //一般函数都添加值的类型,Int 或者float
        //我们这边就要在原来的函数里面添加 定义参数(类型 value)
        musicSlider.onValueChanged.AddListener(MusicVolume);
    }
    public void MusicVolume(float value)
    {
        GetComponent<AudioSource>().volume = musicSlider.value;
    }

   
}

Finally assign both music and script to Slider

 

The game is running, we move the slider in the Game view

Change the value of Value in the component

Also change the Volume of AudioSource to change the volume of the sound

Guess you like

Origin blog.csdn.net/Cddmic/article/details/126704544
Recommended