Hello, I am learning about scripting but I have an issue with DataStore.
I tried to solve it but I couldn’t so I hope someone helps me.
the problem is: The Data is not saving
Here is my code
local DS = game:GetService("DataStoreService")
local myData = DS:GetDataStore("myData")
local Data
game.Players.PlayerAdded:Connect(function(player)
local Leaderstats = Instance.new("Folder",player)
Leaderstats.Name = "leaderstats"
local XP = Instance.new("IntValue",Leaderstats)
XP.Name = "XP"
XP.Value = 0
local Level = Instance.new("IntValue",Leaderstats)
Level.Name = "Level"
Level.Value = 0
local PlayerUserID = "Player_"..player.UserId
--Load Data
local success, errormessage = pcall(function()
Data = myData:GetAsync(PlayerUserID)
end)
if success then
XP.Value = Data.XP
Level.Value = Data.Level
end
end)
--Save Data
game.Players.PlayerRemoving:Connect(function(player)
local PlayerUserId = "Player_"..player.UserId
local Data = {
XP = player.leaderstats.XP;
Level = player.leaderstats.Level;
}
local success, errormessage = pcall(function()
myData:SetAsync(PlayerUserId,Data)
end)
if success then
print("Data has been Saved")
else
print("Data Failed")
end
end)
Yeah what’s your issue that you’re experiencing? Is Data not saving? Give an example. Maybe show us some of your output such as errors if you have any.
I made some adjustments to your script, let me know if this fixes any of your issues.
local DS = game:GetService("DataStoreService")
local myData = DS:GetDataStore("myData")
game.Players.PlayerAdded:Connect(function(player)
local Leaderstats = Instance.new("Folder",player)
Leaderstats.Name = "leaderstats"
local XP = Instance.new("IntValue",Leaderstats)
XP.Name = "XP"
XP.Value = 0
local Level = Instance.new("IntValue",Leaderstats)
Level.Name = "Level"
Level.Value = 0
--Load Data
local success, errormessage = pcall(function()
Data = myData:GetAsync(player.UserId)
end)
if success then
XP.Value = Data[1]
Level.Value = Data[2]
end
end)
--Save Data
game.Players.PlayerRemoving:Connect(function(player)
local DataToSave = {}
local success, errormessage = pcall(function()
for i, val in pairs(player.leaderstats:GetChildren()) do
table.insert(DataToSave, val.Value)
end
myData:SetAsync(player.UserId, DataToSave)
end)
if success then
print("Data has been Saved")
else
print("Data Failed")
end
end)
I’m not sure about that, but you can do autosaving. That’s the best practice for just about anything, because if the player unexpectedly leaves the game (like disconnects), there’s a chance that PlayerRemoving won’t fire for them. I would recommend keeping your current code, but while the player is in the game, have the data automatically be saved, let’s say like every 60-120 seconds.
You can use the system save data ProfileService, this service is good to save Data. That’s system use to Cache for save Data because it’s more fast instead of collecting manually the values. Jaja, sorry for my english.