StorageUtil.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { sys } from "cc"
  2. import { Debug } from "./Debug"
  3. import { PREVIEW } from "cc/env"
  4. type SimpleType = number | string | boolean
  5. const Tag: string = 'StorageUtil'
  6. const Id: string = 'hgxcds'
  7. export class StorageUtil {
  8. public static setItem(key: string, value: SimpleType, log: boolean = true): void {
  9. if (typeof value === "boolean") value = Number(value)
  10. const full_key: string = this.getFullKey(key)
  11. log && Debug.Log(Tag, `保存${full_key},值为:`, value)
  12. sys.localStorage.setItem(full_key, String(value))
  13. }
  14. /**存放对象或者数组 */
  15. public static setObj(key: string, obj: Object | any[], log: boolean = true): void {
  16. let str: string = JSON.stringify(obj)
  17. const full_key: string = this.getFullKey(key)
  18. log && Debug.Log(Tag, `保存${full_key},值为:`, str)
  19. sys.localStorage.setItem(full_key, str)
  20. }
  21. public static getItem(key: string, defaultValue?: SimpleType): any {
  22. const full_key: string = this.getFullKey(key)
  23. let value: string = sys.localStorage.getItem(full_key)
  24. if (value) return JSON.parse(value)
  25. Debug.Log(Tag, `${full_key}使用默认值:`, defaultValue)
  26. return defaultValue
  27. }
  28. /**获取对象或者数组 */
  29. public static getObj(key: string, defaultValue?: Object | any[]): any {
  30. const full_key: string = this.getFullKey(key)
  31. let str: string = sys.localStorage.getItem(full_key)
  32. if (str) return JSON.parse(str)
  33. Debug.Log(Tag, `${full_key}使用默认值:`, defaultValue)
  34. return defaultValue
  35. }
  36. public static removeItem(key: string): void {
  37. const full_key: string = this.getFullKey(key)
  38. sys.localStorage.removeItem(full_key)
  39. }
  40. public static clear(): void {
  41. sys.localStorage.clear()
  42. }
  43. private static getFullKey(key: string): string {
  44. return `${Id}_${key}`
  45. }
  46. }
  47. if (PREVIEW) {
  48. globalThis.StorageUtil = StorageUtil
  49. }