游戏场景——游戏界面——设置界面复用

先将开始场景当中的设置面板复制过来

由于设置面板挂载的脚本都是相同的,在BeginScene中关闭设置面板时不会报空,而在GameScene中关闭设置面板时却会报空,这是因为监听事件中的单例模式调用的实例是BeginPanel,而不是GamePanel。要解决这个问题只需要利用场景判断的API来判断当前场景是否是BeginScene即可。

settingPanel脚本中写这个代码即可

并且还要将开始场景当中的bgm复制过来,这也是为了防止报空

总结:

直到当前SettingPanel的代码为

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.SceneManagement;public class SettingPanel : BasePanel{//关联的各按钮控件public CustomGUISlider sliderMusic;public CustomGUISlider sliderSound;public CustomGUIToggle toggleMusic;public CustomGUIToggle toggleSound;public CustomGUIButton btnExit;void Start(){//事件监听sliderMusic.changeValue += (value) => GameDataMgr.Instance.ChangeBKValue(value);sliderSound.changeValue += (value) => GameDataMgr.Instance.ChangeSoundValue(value);toggleMusic.changeValue += (value) => GameDataMgr.Instance.OpenOrCloseBKMisic(value);toggleSound.changeValue += (value) => GameDataMgr.Instance.OpenOrCloseSound(value);btnExit.clickEvent += () =>{HideMe();if (SceneManager.GetActiveScene().name == "BeginScene"){BeginPanle.Instance.ShowMe();}};HideMe();}//数据更新函数public void UpdatePanelInfo(){//获得musicData这个变量的信息MusicData data = GameDataMgr.Instance.musicData;//对自己的变量进行赋值sliderMusic.nowValue = data.bkValue;sliderSound.nowValue = data.soundValue;toggleMusic.isSel = data.isOpenBK;toggleSound.isSel = data.isOpenSound;}//重写虚函数public override void ShowMe(){base.ShowMe();//在每次显示面板时就要更新数据UpdatePanelInfo();}public override void HideMe(){base.HideMe();Time.timeScale = 1;}}