Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

my data only saves half the time?

Asked by 4 years ago

only half the time in roblox studio does the game save my deaths and kills and print "data saved" when i leave. The other half of the time it doesn't print anything. please help.

local dataStoreService = game:GetService("DataStoreService")
local myDataStore = dataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:connect(function(player)

    local leaderstats = Instance.new("Folder",player)
    leaderstats.Name = "leaderstats"

    local kills = Instance.new("IntValue",leaderstats)
    kills.Name = "Kills"

    local deaths = Instance.new("IntValue",leaderstats)
    deaths.Name = "Deaths"


    local dataSave
    local success, errormsg = pcall(function()
        dataSave = myDataStore:GetAsync(player.UserId)
    end)

    if success then
        deaths.Value = dataSave.deaths
        kills.Value = dataSave.kills
    else
        warn(errormsg)
        print("Data not saved")
    end
end)

game.Players.PlayerRemoving:Connect(function(plr)

    local oldDataSave = {
        deaths = plr.leaderstats.Deaths.Value;
        kills = plr.leaderstats.Kills.Value;
    }


    local success, errormsg = pcall(function()
        myDataStore:SetAsync(plr.UserId,oldDataSave)
    end)

    if success then
        print("Data saved")
    elseif errormsg then
        print("Data not saved")
        warn(errormsg)
    end
end)

1 answer

Log in to vote
0
Answered by
iuclds 720 Moderation Voter
4 years ago

I'm renewing your code

local code = game:GetService('DataStoreService'):GetDataStore('0')
local default = {Kills = 0, Deaths = 0}
local data = {}

function inckills(player, number)
    data[player.Name].Kills = data[player.Name].Kills + number
    print(data[player.Name].Kills)
end

function incdeaths(player, number)
    data[player.Name].Deaths = data[player.Name].Deaths + number
    print(data[player.Name].Deaths)
end

game.Players.PlayerAdded:Connect(function(player)
    data[player.Name] = code:GetAsync(Player.UserId) or default

    inckills(player, 2)
    incdeaths(player, 2)
end)

game.Players.PlayerRemoving:Connect(function(player)
    code:SetAsync(Player.UserId, data[player.Name])
    data[player.Name] = nil
end)


0
Edit as you like. iuclds 720 — 4y
Ad

Answer this question