当前位置:网站首页>音乐播放(Toggle && PlayerPrefs)
音乐播放(Toggle && PlayerPrefs)
2022-07-06 09:18:00 【SQ刘】
Toggle控制音乐播放,并利用PlayerPrefs保存上次是否勾选时的记录
1、新建工程。
2、拖入事先准备好的音乐(只要是音乐都行)。
3、随便添加一个物体(我这里以Cube为例),给它添加Audio Source组件,在AudioClip中拖入音乐素材,勾选上Play On Awake和Loop,如下图所示。
4、添加UI | Panel,并在Panel下面添加Toggle单选框,如下图所示。
5、添加Music脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Music : MonoBehaviour
{
public Toggle musicToggle;
public AudioSource musicAudio;
private void Awake()
{
if (PlayerPrefs.HasKey("MusicOn"))
{
if (PlayerPrefs.GetInt("MusicOn") == 1)
{
musicToggle.isOn = true;
musicAudio.enabled = true;
}
else
{
musicToggle.isOn = false;
musicAudio.enabled = false;
}
}
else
{
musicToggle.isOn = true;
musicAudio.enabled = true;
}
}
public void MusicSwitch()
{
//通过判断单选框是否被勾选上,从而来决定是否播放背景音乐
if (musicToggle.isOn == false)
{
musicAudio.enabled = false;
//保存音乐开关的状态,0代表关闭,1代表开启
PlayerPrefs.SetInt("MusicOn", 0);
}
else
{
musicAudio.enabled = true;
PlayerPrefs.SetInt("MusicOn", 1);
}
PlayerPrefs.Save(); //保存上次是否勾选时的记录
}
}
6、回到Unity3D,拖入Music Toggle 和 Music Audio。
7、给开关注册事件。
8、完成。
边栏推荐
- [offer9] implement queues with two stacks
- Office prompts that your license is not genuine pop-up box solution
- Mysql database index
- First use of dosbox
- (5) Introduction to R language bioinformatics -- ORF and sequence analysis
- JS變量類型以及常用類型轉換
- JS variable types and common type conversions
- FairyGUI循环列表
- 2022.2.12 resumption
- Unity scene jump and exit
猜你喜欢
Mysql database index
Teach you to release a DeNO module hand in hand
Walk into WPF's drawing Bing Dwen Dwen
Pat 1097 duplication on a linked list (25 points)
dosbox第一次使用
(3) Introduction to bioinformatics of R language - function, data Frame, simple DNA reading and analysis
Problèmes avec MySQL time, fuseau horaire, remplissage automatique 0
Fabrication of fairygui simple Backpack
(5) Introduction to R language bioinformatics -- ORF and sequence analysis
NRF24L01故障排查
随机推荐
FairyGUI循环列表
1081 rational sum (20 points) points add up to total points
Redis based distributed locks and ultra detailed improvement ideas
程序设计大作业:教务管理系统(C语言)
Combination of fairygui check box and progress bar
InnoDB dirty page refresh mechanism checkpoint in MySQL
Fairygui joystick
[Offer29] 排序的循环链表
[leetcode15] sum of three numbers
FairyGUI簡單背包的制作
(三)R语言的生物信息学入门——Function, data.frame, 简单DNA读取与分析
Unity scene jump and exit
Unity3d, Alibaba cloud server, platform configuration
SSD technical features
Programming homework: educational administration management system (C language)
Common DOS commands
Basic operations of databases and tables ----- creating data tables
1041 Be Unique (20 point(s))(哈希:找第一个出现一次的数)
Conditional probability
(core focus of software engineering review) Chapter V detailed design exercises