SettingData.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { _decorator, sys } from 'cc';
  2. import { Singleton } from '../core/manager/Singleton';
  3. import Utils from '../core/utils/Utils';
  4. import { GameConst } from '../core/common/GameConst';
  5. const { ccclass, property } = _decorator;
  6. @ccclass("SettingData")
  7. class SettingData extends Singleton{
  8. private _data: any = null;
  9. public get data() {
  10. if (!this._data) {
  11. this.loadFromCache();
  12. }
  13. return this._data;
  14. }
  15. /**
  16. * 读取数据缓存
  17. */
  18. public loadFromCache(){
  19. let l = sys.localStorage.getItem(GameConst.localCache.settingData);
  20. if(l){
  21. this._data = JSON.parse(Utils.decrypt(l));
  22. }else{
  23. //没有数据保存一份默认的初始数据
  24. this._data = {
  25. bgMusic: true,//背景音乐开关
  26. soundFx: true,//音效开关
  27. vibration: false//震动开关
  28. }
  29. this.saveToCache();
  30. }
  31. return this.data;
  32. }
  33. /**
  34. * 得到设置的数据数组
  35. */
  36. public getSettingDatas() {
  37. const displayNames = ["背景音乐", "音效", "震动"];
  38. const dataKeys = Object.keys(this.data);
  39. // 确保字段顺序一致
  40. return dataKeys.map((key, index) => ({
  41. name: displayNames[index],
  42. selected: this.data[key]
  43. }));
  44. }
  45. /**
  46. * 保存到缓存中
  47. */
  48. public saveToCache(){
  49. const data = JSON.stringify(this.data);
  50. //序列化JSON字符串过后加密存储
  51. sys.localStorage.setItem(GameConst.localCache.settingData, Utils.encrypt(data));
  52. }
  53. /**
  54. * 删除缓存
  55. */
  56. public remove(){
  57. sys.localStorage.removeItem(GameConst.localCache.settingData);
  58. this.loadFromCache();
  59. }
  60. }
  61. //全局单例
  62. export const settingData = SettingData.ins();