Persistent Player Storage Data

-- Contributed by: FearTheDev(John) (user @) CoreGames.com

function OnResourceChanged(player, resource, value)

    -- Get player stored data
    local playerData = Storage.GetPlayerData(player)
    
    -- If the player does not have resource data table then create one.
    if type(playerData.resources) ~= "table" then
        playerData.resources = {}
    end

    playerData.resources[resource] = value
    Storage.SetPlayerData(player, playerData)
end

function EquipToPlayer(player, equipmentAsset)
    -- Spawn asset by templateId
    local instance = World.SpawnAsset(equipmentAsset)

    --If the player is valid then equip the asset otherwise destroy it.
    if Object.IsValid(player) then
        print("Equipped "..instance.name.." to "..player.name.."..")
        instance:Equip(player)
    else
        instance:Destroy()
    end
end

function OnPlayerJoined(player)

    -- Get player stored data
    local playerData = Storage.GetPlayerData(player)
    local equipped = false
    
    -- If the player does not have a equipment data table then create one.
    if type(playerData.equipment) ~= "table" then
        playerData.equipment = {}
    end

    -- If the player does not have resource data table then create one.
    if type(playerData.resources) ~= "table" then
        playerData.resources = {}
    end

    -- Set the resources of the player to their saved resources.
    for resource, value in pairs(playerData.resources) do
        player:SetResource(resource, value)
    end

    if Object.IsValid(player) then
        for _, equipmentAssetId in pairs(playerData.equipment) do
            Task.Spawn(function() EquipToPlayer(player, equipmentAssetId) end)
            equipped = true
        end
    end

    -- Initialize event listening for when a resource has been changed.
    player.resourceChangedEvent:Connect(OnResourceChanged)

    if playerData.location then
        player:SetWorldPosition(playerData.location)
    end

function OnPlayerLeft(player)
    local playerData = Storage.GetPlayerData(player)

    playerData.location = player:GetWorldPosition()

    Storage.SetPlayerData(player, playerData) 
end

Game.playerJoinedEvent:Connect(OnPlayerJoined)
Game.playerLeftEvent:Connect(OnPlayerLeft)

Latest Posts