So I’m trying to save a player’s money and for some reason the following script isn’t working. The messages are printing but either the data is not saving OR the data isn’t loading correctly. I’m not really sure how to check that. One thing I should mention is that print(data) isn’t giving anything if that helps.
local players = game.Players
local datastoreservice = game:GetService("DataStoreService")
function GetPlayerData(player) --function for getting player's data when they join
local playerdata = datastoreservice:GetDataStore("PlayerData")
local success,data = pcall(function()
playerdata:GetAsync(player.UserId)
end)
if not success then
wait(.5)
GetPlayerData(player)
else if success then
if data then
print(data)
player:WaitForChild("leaderstats").Money.Value = data
else print("player has no data")
end
end
end
print("Player has " .. player:WaitForChild("leaderstats").Money.Value)
end
function onPlayerEntered(player) --function for creating data when a player joins
local stats = Instance.new("Folder")
stats.Name = "leaderstats"
stats.Parent = player
local money = Instance.new("IntValue")
money.Name = "Money"
money.Value = 100
money.Parent = stats
GetPlayerData(player)
end
players.PlayerAdded:Connect(onPlayerEntered)
function SavePlayerData(player) --saving player's data when they leave
local playerdata = datastoreservice:GetDataStore("PlayerData")
local value = player:WaitForChild("leaderstats").Money.Value
local success,err = pcall(function()
playerdata:SetAsync(player.UserId, value)
print(player:WaitForChild("leaderstats").Money.Value)
end)
if success then
print("sucessfully saved " .. player.Name .. "'s data")
else
wait(.5)
SavePlayerData(player)
end
end
players.PlayerRemoving:Connect(function(player)
print(player.Name .. " has left the server, saving data")
SavePlayerData(player)
end)
game:BindToClose(function(player)
print("Bind to close activated, saving data")
for _, client in ipairs(players:GetPlayers()) do
SavePlayerData(client)
end
end) ```