The GetSave variable on line 10 is returning a nil value even tho a player has played before on the actual roblox game, not on roblox studio. This is basically causing my script to reset the player's data. Can someone help and explain why?
DataStore = game:GetService("DataStoreService")
Players = game:GetService("Players")
ServerStorage = game:GetService("ServerStorage")
SaveFolder = ServerStorage:WaitForChild('SaveFolder')
DataStorage = DataStore:GetDataStore('test1')
Players.PlayerAdded:connect(function(player)
local key = player.UserId
local GetSave = DataStorage:GetAsync(key)
print(GetSave)
local PlayerFolder = Instance.new("Folder", player)
PlayerFolder.Name = 'PlayerStats'
for i, stats in pairs(SaveFolder:GetChildren()) do
local NewStats = Instance.new(stats.ClassName, PlayerFolder)
NewStats.Name = stats.Name
NewStats.Value = stats.Value
end
if GetSave then -- if player has data saved
print(player .. ' has available data')
for i, stats in pairs(PlayerFolder:GetChildren()) do
local StatsKey
local success, failure = pcall(function()
StatsKey = key .. '-' .. stats.Name
DataStorage:GetAsync(StatsKey)
end)
if success then
stats.Value = StatsKey
print('Loaded ' .. stats.Value .. ' to ' .. stats.Name)
else
print('Error when getting data')
warn(failure)
end
end
else -- Setting default data to player
print('Setting default data to player')
for i, stats in pairs(SaveFolder:GetChildren()) do
PlayerFolder:FindFirstChild(stats.Name).Value = stats.Value
end
end
end)
Players.PlayerRemoving:Connect(function(player)
local key = player.UserId
local PlayerFolder = player:WaitForChild('PlayerStats')
for i, stats in pairs(PlayerFolder:GetChildren()) do
local StatsKey
local success, failure = pcall(function()
StatsKey = key .. '-' .. stats.Name
DataStorage:SetAsync(StatsKey, stats.Value)
end)
if success then
stats.Value = StatsKey
print(StatsKey .. ' was saved')
else
print('Error when saving data')
warn(failure)
end
end
end)

3 comments
Is this a local script?
It's in a server script in ServerScriptService
Mostly the reason because data doesn't save is because the user is trying to save data by changing values through the client.