Unity2D声音控制面板Demo
程序员文章站
2024-03-18 22:33:16
...
没有咋优化(咕咕咕)的声音面板Demo源码(之前学习Unity的笔记)
出来的面板滑动滑动条按钮会动态控制音量大小
如果不保存设置,音量会是之前载入时候的音量
Welcome是这个游戏关联的开始场景类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class SettingPanel : MonoBehaviour
{
public Button btn_Reset;
public Button btn_Apply;
public Button btn_Close;
public Slider musicSlider;
public Slider soundSlider;
public static int musicValue = 100;
public static int soundValue = 100;
public Text labelMusic;
public Text labelSound;
public static bool save = false;
private static int tempMusicValue;
private static int tempSoundValue;
public static SettingPanel Instance;
void Awake()
{
if (Instance == null)
Instance = this;
}
private void AddEventHandle()
{
btn_Reset.onClick.AddListener(() => ResetSetting());
btn_Apply.onClick.AddListener(() => SaveSetting());
btn_Close.onClick.AddListener(() => Close());
musicSlider.onValueChanged.AddListener((float value) => ChangeMusicValue(Mathf.RoundToInt(value)));
soundSlider.onValueChanged.AddListener((float value) => ChangeSoundValue(Mathf.RoundToInt(value)));
}
void Close()
{
SoundPacks.soundPacks.PlayClickSound();
if (save == false)
{
musicValue = tempMusicValue;
soundValue = tempSoundValue;
LoadValue();
ChangeMusicValue(tempMusicValue);
}
GameObject.Destroy(this.gameObject);
}
private void SaveSetting()
{
SoundPacks.soundPacks.PlayClickSound();
save = true;
}
private void LoadValue()
{
labelMusic.text = musicValue.ToString();
labelMusic.text = soundValue.ToString();
musicSlider.value = musicValue;
soundSlider.value = soundValue;
}
private void ResetSetting()
{
SoundPacks.soundPacks.PlayClickSound();
musicValue = 100;
soundValue = 100;
LoadValue();
}
private void ChangeMusicValue(int value)
{
labelMusic.text = value.ToString();
musicValue = value;
float f = musicValue / 100f;
Welcome.bgm.GetComponent<AudioSource>().volume = f;
}
private void ChangeSoundValue(int value)
{
labelSound.text = value.ToString();
soundValue = value;
}
public static void ShowSetting()
{
SoundPacks.soundPacks.PlayClickSound();
var req = Resources.Load<SettingPanel>("prefabs/settingpanel");
var obj = GameObject.Instantiate(req);
obj.AddEventHandle();
obj.LoadValue();
save = false;
tempMusicValue = musicValue;
tempSoundValue = soundValue;
var upper = Welcome.Instance.upperLayer;
obj.transform.SetParent(upper.transform);
obj.gameObject.SetActive(true);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
Close();
}
}
图片素材没有资源,只有源码。
欢迎交流指正
上一篇: SparkSql 思维导图整理