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

script to store data for coins but when i leave it doesnt save what did i do wrong??

Asked by 2 years ago
Edited by chess123mate 2 years ago

here is my script for the data store

local DataStoreService = game:GetService("DataStoreService")

local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local cash = Instance.new("IntValue")
        cash.Name = "Cash"
        cash.Parent = leaderstats

    local data  
    local success, errormessage = pcall(function()
        data = myDataStore:GetAsync(player.UserId.."-cash")
    end)

    if success then
        cash.Value = data
    else
        print("There was a error whilist getting your data")
        warn(errormessage)
    end
end)

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

    local success, errormessage = pcall(function()
        myDataStore:GetAsync(player.UserId.."-cash",player.leaderstats.Cash.Value)
    end)

    if success then
        print("Player Data sccessfully saved!")
    else
        print("There was a error when saving your data")
        warn(errormessage)
    end

end)
0
(I've edited your question to add the code block - there's a little "Lua" icon you can click (to the right of Bold/Italics/etc) for it.) chess123mate 5873 — 2y

1 answer

Log in to vote
0
Answered by 2 years ago
  1. You need to use SetAsync not GetAsync when the player leaves
  2. You need to use game:BindToClose to make sure that the server stays open after all players leave long enough to save their data.

Alternatively, if you use something like ProfileService, it takes a bit of getting used to, but it handles all that in addition to auto-saving, session locking, and more.

Ad

Answer this question