As you’ve seen in the title, my currency and other datastores in my game are only saving and working properly when I play in Roblox Studio but they are not saving/working properly in game. I don’t know why this error is happening, but if you do, please feel free to reply down below. Here is my code below:
game.Players.PlayerAdded:Connect(function(player)
items = {}
for i=1, 1000, 1 do
table.insert(items, false)
end
local folder = Instance.new("Folder")
folder.Name = "leaderstats"
folder.Parent = player
local currency = Instance.new("IntValue")
currency.Name = currencyName
currency.Parent = folder
local ID = currencyName.."-"..player.UserId
local playerKey = "Player_" .. player.UserId
local savedData = nil
getdatastore = nil
coinquestdata = nil
levelquestdata = nil
pcall(function()
savedData = DataStore:GetAsync(ID)
getdatastore = ItemsDatastore:GetAsync(player.UserId)
coinquestdata = CoinQuestDatastore:GetAsync(player.UserId)
levelquestdata = LevelQuestDatastore:GetAsync(player.UserId)
end)
if savedData ~= nil then
currency.Value = savedData
print("Data loaded")
else
-- New player
currency.Value = 0
print("New player to the game")
end
if getdatastore ~= nil then
for i, v in pairs(getdatastore) do
if getdatastore[i] == true then
if remotetrailevents[i] then
remotetrailevents[i]:FireClient(player)
end
end
end
else
ItemsDatastore:GetAsync(player.UserId, items)
end
local QuestGui = player.PlayerGui:WaitForChild("QuestGui")
if coinquestdata ~= nil then
QuestGui.Frame.MainFrame.Quest1.CoinAmount.Text = coinquestdata
game.ReplicatedStorage.Events:WaitForChild("CoinQuestDataLoaded"):FireClient(player)
end
if levelquestdata ~= nil then
QuestGui.Frame.MainFrame.Quest2.CoinAmount.Text = levelquestdata
game.ReplicatedStorage.Events:WaitForChild("LevelQuestDataLoaded"):FireClient(player)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local ID = currencyName.."-"..player.UserId
local variable = player.PlayerGui.QuestGui.Frame.MainFrame
local success, err = pcall(function()
CoinQuestDatastore:SetAsync(player.UserId, variable.Quest1.CoinAmount.Text)
DataStore:SetAsync(ID,player.leaderstats[currencyName].Value)
end)
end)
game:BindToClose(function()
-- When game is ready to shutdown
for i, v in pairs(game.Players:GetPlayers()) do
local ID = currencyName.."-"..v.UserId
local variable = v.PlayerGui.QuestGui.Frame.MainFrame
CoinQuestDatastore:SetAsync(v.UserId, variable.Quest1.CoinAmount.Text)
DataStore:SetAsync(ID,v.leaderstats[currencyName].Value)
end
wait(5)
end)