local DataStoreService = game:GetService("DataStoreService")
local Save = DataStoreService:GetDataStore("Save")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local Levels = Instance.new("IntValue", leaderstats)
Levels.Name = "Levels"
local XP = Instance.new("IntValue", leaderstats)
XP.Name = "XP"
--DataStore
local playerUserId = player.UserId
local Data
--local ok, errorMessage = pcall(function()
Data = Save:GetAsync(playerUserId)
--end)
--if ok == true then
print("Data Loaded!")
Levels.Value = Data[1]
XP.Value = Data[2]
--else
-- print("Error Loading Data")
-- error(errorMessage)
--end
end)
game.Players.PlayerRemoving:Connect(function(player)
--DataStore
local playerUserId = player.UserId
local ok, errorMessage = pcall(function()
local DTS = {player.leaderstats.Levels.Value, player.leaderstats.XP.Value}
Save:SetAsync(playerUserId, DTS)
end)
if ok == true then
print("Data Saved!")
else
print("Error Saving Data")
error(errorMessage)
end
end)
Hi!
Seems quite right to me after testing it a little bit in studio.
Make sure you keep those extra if statements if there is data to be found though, there will be no data for any new players that join until they leave, and since you’re trying to index something that is nil, it will error.
To 100% make sure your datastores actually work while testing, Always enable Studio Access to API if you are testing datastores in studio.
Although the code is relatively the same, this is what is in my test place:
local DataStoreService = game:GetService("DataStoreService")
local Save = DataStoreService:GetDataStore("Save")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local Levels = Instance.new("IntValue", leaderstats)
Levels.Name = "Levels"
local XP = Instance.new("IntValue", leaderstats)
XP.Name = "XP"
--DataStore
local playerUserId = player.UserId
local Data
local ok, errorMessage = pcall(function()
Data = Save:GetAsync(playerUserId)
end)
if Data then
Levels.Value = Data[1]
XP.Value = Data[2]
end
end)
game.Players.PlayerRemoving:Connect(function(player)
--DataStore
local playerUserId = player.UserId
local ok, errorMessage = pcall(function()
local DTS = {player.leaderstats.Levels.Value, player.leaderstats.XP.Value}
Save:SetAsync(playerUserId, DTS)
end)
if ok == true then
print("Data Saved!")
else
print("Error Saving Data")
error(errorMessage)
end
end)
Also, please make sure to be a little more specific so developers can help you as soon as possible. I hope this works for you and please make sure to mark as solution if it’s correct
2 Likes
Sorry for the delay. Thank you! Works perfectly.