Hey fellow developers, I have trouble with my data store script that used to work fine. It seems that the code works but saving is not possible even with API Requests turned on. I made it a long time ago following a tutorial and it used to work just fine. I haven’t messed with it at all in fear that i break it completely. Any help is appreciated!
Code
-- By TaxWasTaken --
-- Variables.
local DataStoreService = game:GetService("DataStoreService")
local dataStore = DataStoreService:GetDataStore("datakey")
local playerss = game:GetService("Players")
-- Load data.
playerss.PlayerAdded:Connect(function(player)
-- Creating all the data inside the player.
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local coins = Instance.new("IntValue", leaderstats)
coins.Name = "Coins"
local DataFolder = Instance.new("Folder", player)
DataFolder.Name = "Data"
local missions = Instance.new("Folder", DataFolder)
missions.Name = "MissionsDone"
local points = Instance.new("IntValue", DataFolder)
points.Name = "Points"
points.Value = 150
-- Loading the data.
local PlayerKey = "PLR-"..player.UserId
local data
local success, errormessage = pcall(function()
data = dataStore:GetAsync(PlayerKey)
end)
if success then
coins.Value = data.coins;
points.Value = data.points;
print(player.Name.."'s data was loaded.")
else
points.Value = 150
print(player.Name.." just joined!")
end
end)
-- Saving data.
playerss.PlayerRemoving:Connect(function(player)
local PlayerKey = "PLR-"..player.UserId
-- Table for all the values.
local data = {
coins = player.leaderstats.coins.Value;
points = player.Data.points.Value;
}
-- Saving data.
local success, errormessage = pcall(function()
dataStore:SetAsync(PlayerKey, data)
end)
-- Checking.
if success then
print(player.Name.."'s data was successfully saved.")
else
print("There was an error loading "..player.Name.."'s data.")
warn(errormessage)
end
end)
Are you sure the code provided corresponds to the error in the output? I don’t see a line of code containing presents, and line 38 only directs to if success then which isn’t an issue.
Alongside, your code may not save the data as the server could shutdown before it firesPlayerRemoving event. Utilise game:BindToClose() as your secondary option of saving data.
To improve your code when saving data in addition, I’d replace DataStore:SetAsync() with DataStore:UpdateAsync(function()), but this is optional. I recommend this as it doesn’t possess overwriting flaws (when there’s more than one server saving data), or when you need to need the current table.