有没有什么办法能把cocos类变成键值对

我有一个配置类,里面包含了一些游戏配置,没有多少文本,我想保存到会话中,但是一个一个属性的保存太麻烦了,我就想换成键值对直接保存,有没有什么办法

复制粘贴交给ai

1赞

我觉得你似乎该去学习下ts语言,你到时候会有很大收获

合并为一个Config类?把它设置为static。转换为json?

搞成配置文件啊,没必要写死在代码里

我也想到这个了,但是这样的话我更改了这个以后,我其他调用的地方也还得全都改掉,也没避免了麻烦

主要是想在不影响我其他代码的情况下进行改变

细说一下,可以私信。我想我应该能给你解决

全部改成你要的形状,这个cocos类里全改成 get/set

就是我这个类包含了很多静态的属性,我在其他类中调用了,我想要把这些属性保存到localStorage中,保存玩家现在的游戏状态,但是如果一条一条属性的保存的话,需要保存好几条很麻烦,我就想着能不能把整个类都保存,我也想过把所有的数据现在变成一个大的对象,但是这样的话我别的脚本中调用的就需要进行更改,我想要在不更改其他脚本的情况下,把这些数据一次性保存到localStorage中

你要的应该是这个

//注册持久存储
function regLocalStorage(storageKey: string) {
    return (target, propertyKey: string) => {
        Object.defineProperty(target, propertyKey, {
            get: function (): number {
                return cc.sys.localStorage.getItem(storageKey);
            },
            set: function (val: string) {
                if (val == null)
                    cc.sys.localStorage.removeItem(storageKey);
                else
                    cc.sys.localStorage.setItem(storageKey, val);
            },
        });
    }
}
export default Name {
     @regLocalStorage("coins")
      private  myCoins: string="123";
}

具体就是, 在你要存储到localstore的变量上加上就行

遍历类的静态成员属性?js应该可以,获取反射数据的方式挺多。问下AI

这样就清晰多了,这不已经有人给出了用装饰器写的,应该能满足你的需求了

这个是自动保存吗,需要调用吗

加上了然后呢,好像没什么效果

你全是static 还不一样 去掉static

export default Name {
     @regLocalStorage("coins")
      myCoins: string="123";
}
function regLocalStorage(storageKey: string) {
    return (target, propertyKey: string) => {
        Object.defineProperty(target, propertyKey, {
            get: function (): number {
                if (this["_"+propertyKey]) return this["_"+propertyKey]
                else {
                    this["_"+propertyKey] = cc.sys.localStorage.getItem(storageKey); //做缓存
                }
                return this["_"+propertyKey]
            },
            set: function (val: string) {
                if (this["_"+propertyKey] != undefined && val == this["_"+propertyKey]) return
                if (val == null)
                    cc.sys.localStorage.removeItem(storageKey);
                else {
                    this["_"+propertyKey] = val
                    cc.sys.localStorage.setItem(storageKey, val);
                }
            },
        });
    }
}

我有个问题,这个static是为了方便我别的脚本获取这里的属性,我去掉了怎么获取呀

class Test {
@regLocalStorage(“XXXX”)
myCoins: string = “123”;

}

export const test = new Test()
其他ts文件

test .myCoins

他这个装饰器的原理是什么啊,为什么我保存不了

静态配置写一个const 不就行了 动态的看文档 local storage