我如何将玩家的购买保存到 DataStore?

How would I save a player's purchases to DataStore?

所以我正在和我的朋友一起开发游戏,我们有这些游戏升级可以解锁新东西,但我想知道如何保存它们?

我的购买模块是这样设置的:

local module = {}

local Upgrades = {
    { id = "idForThing", cash = 20, callback = function(player) 
        -- hi!
    end, unlimitedPurchases = true, purchased = false }
}

module.getUpgrade = function(upgradeID)
    for i, upg in pairs(Upgrades) do
        if upg.id == upgradeID then
            return upg
        else
            continue
        end
    end
    return nil
end

module.getUpgrades = function()
    return Upgrades
end

module.purchaseUpgrade = function(player, upgradeID)
    for i, upg in pairs(Upgrades) do
        if upg.id == upgradeID then
            if upg.purchased then
                SFX.Error:Play()
                break
            end
            if game:GetService("ServerStorage").Cash.Value >= upg.cash then
                game:GetService("ServerStorage").Cash.Value -= upg.cash
                upg.purchased = not upg.unlimitedPurchases
                upg.callback(player)
                SFX.Purchased:Play()
            else
                SFX.Error:Play()
            end
            break
        else
            continue
        end
    end
end

return module

所以,基本上在升级中 table 它有包含 5 个值的项目。

商品编号

花费的金额

购买时运行的代码

如果属实,您可以多次购买该商品

当玩家购买物品时更改为 true

我做了 module.getUpgrades,希望我可以将升级 table 复制到 DataStore,但它也会复制我不想要的现金。我只是想让它复制 id 和购买的价值。那么我如何只复制 ID 和购买价值?

您可以通过将键设置为 nil table[key] = nil(或 table.remove,如果您有数组)从 table 中删除键。然而,这里还有一个问题,即 lua table 是通过引用传递的,因此我们不想从 getUpgrades 的返回值中删除,因为它将从 Upgrades table 还有

假设您的 DataStore 有一些函数 insert(...) 需要 table 并将其放入数据存储;相反,我们可以做的是只使用我们想要的键创建一个新的 table,例如:

local upgrades = module.getUpgrades(id)
local insert_tbl = { id = upgrades.id, purchased = upgrades.purchased }
DataStore.insert(insert_tbl)

您可以像这样returnid值和购买值。

-- for returning single upgrade
module.getUpgrade = function(upgradeID)
    for i, upg in pairs(Upgrades) do
        if upg.id == upgradeID then
            return {id = upg.id, purchased = upg.purchased}
        else
            continue
        end
    end
    return nil
end
-- for multiple upgrades just loop through the table
module.getUpgrades = function()
    res = {}
    for i, v in pairs(Upgrades)do
       table.insert(res,{id = v.id, purchased = v.purchased})
    end
    return res
end

如果你知道自己在做什么,你可以忽略我剩下的回答。

您需要调用 moduleName.getUpgrades() 进行保存。

local moduleName = require("YourModuleName")

-- To save, just call the function inside the setAsync
PlayerSavesU:SetAsync(player.UserId, moduleName.getUpgrades())

-- To use the retrieved data from GetAsync();
local data = PlayerSavesU:GetAsync(player.UserId);
if(data ~= nil) then
    for i,v in pairs(data) do
        print(v.id, v.purchased)
    end
end

不过,此代码可能有效。它仍然不是很有用,因为它不知道哪个玩家购买了这些物品。所以你需要添加一种方法来识别每个玩家。