Hello im trying to make a data store system but for some reason it doesnt save. There are no errors in the output or script analysis, and the few print lines i set up to see where the code stops, the last print i see in the output window is "This part loaded". I dont know why it doesnt work and i got no idea on how to fix it, heres my code:
local dataStoreService = game:GetService("DataStoreService")
local myDataStore = dataStoreService:GetDataStore("myDataStore")
print("Succesfully loaded dataStoreService and myDataStore")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Cookies = Instance.new("IntValue", leaderstats)
Cookies.Name = "Cookies"
Cookies.Value = 0
Cookies.Parent = leaderstats
playerUserId = "Player_"..player.UserId
print("Leaderstats made")
-- load data
local data
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(playerUserId)
end)
if success then
-- set data
Cookies.Value = data
end
print("This part loaded")
end)
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = "Player_"..player.UserId
local data = player.leaderstats.Cookies.Value
local success, errormessage = pcall(function()
myDataStore:SetAsync(playerUserId, data)
end)
print("This thing happened")
if success then
print("Data successfully saved")
else
print("Error happened")
warn(errormessage)
end
print("Script ended")
end)
Something id also like to mention is that anything i want to print can print fine in the output window before i reach the myDataStore:SetAsync(playerUserId, data). Anything after it wont work. Thanks for help.
EDIT: Attempted to replace the PlayerRemoving with the following and i got an error saying "ServerScriptService.leaderstatshandler:51: attempt to index nil with 'UserId'", heres my code:
game:BindToClose(function(player)
local playerUserId = "Player_"..player.UserId
local data = player.leaderstats.Cookies.Value
local success, errormessage = pcall(function()
myDataStore:SetAsync(playerUserId, data)
end)
print("This thing happened")
if success then
print("Data successfully saved")
else
print("Error happened")
warn(errormessage)
end
print("Script ended")
end)

3 comments
Same Problem
Just a quick check, are API Services enabled?
Yes, they are