You can write your topic however you want, but you need to answer these questions:
What do you want to achieve? Keep it simple and clear!
My datastore script isnt working for some reason, ive tried so many ways but none work
What is the issue?
local DatastoreService = game:GetService("DataStoreService")
local SaveStore = DatastoreService:GetDataStore("SaveStore")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local Coins = Instance.new("IntValue", leaderstats)
Coins.Name = "Coins"
local Key = "Player_".. player.UserId
local Data
local success, errormessage = pcall(function()
Data = SaveStore:GetAsync(Key)
end)
if success then
if Data ~= nil then
Coins.Value = Data.Coins
end
else
Coins.Value = 0
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local leaderstats = player.leaderstats
local SavedData = {
Coins = leaderstats.Coins.Value
}
local success, errormessage = pcall(function()
SaveStore:SetAsync("Player_".. player.UserId, SavedData)
end)
for i,v in pairs(player.leaderstats:GetChildren()) do
table.insert(SavedData, v.Value)
end
end)
This is my script, i plan on adding more values in the future, thats why I have used a table
I can’t discern any immediate issue with your code. How exactly do you know that your DataStore script isn’t working? Are you changing the values and those aren’t saving? If so, how exactly are you changing them? If you change them while in the client view of test mode, that simulates a client-sided change and will not propagate to the server, thus the server will not see the new value you set.
local Data
local success, errormessage = pcall(function()
Data = SaveStore:GetAsync(Key) or {} --since you're getting a table.
end)
if success and Data ~= {} then
Coins.Value = Data.Coins
print("Success:", Data.Coins)
elseif errormessage then warn(errormessage) end
Since you’re only using Players.PlayerRemoving, you could also implement game:BindToClose() function to fire when the server closes - there are occurrences that the server shutdowns before listening to the PlayerRemoving event.
I’ve also noticed you’re trying to save other values after :SetAsync().
Edit: I’ve noticed that the leaderstats, and the coins, are being parented with a second parameter. Try parenting them with .Parent (if it doesn’t show).
It is probably because you are not using :BindToClose() to secure the data save after the server is closed, this happens because the server closes before the PlayerRemoving event can even fire. So to fix this you will need to add to your code:
game:BindToClose(function()
for i, client in pairs(game.Players:GetPlayers()) do
local SavedData = {
client.leaderstats.Coins.Value
}
SaveStore:SetAsync("Player_".. client.UserId, SavedData)
end
end)
I had the same issue some months ago and this solved it, not sure why it doesn’t happen to some people, but even if it works it’s better to give it this security.