What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I looked on the DevHub but it didn’t show how to fix my problem.
Here is my code:
local ds = game:GetService("DataStoreService")
local data = ds:GetDataStore("Data")
game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder",plr)
leaderstats.Name = "leaderstats"
local stage = Instance.new("NumberValue",leaderstats)
stage.Name = "Stage"
local plrdata = data:GetAsync(plr.UserId)
stage.Value = table.unpack(plrdata,1,1) or 0
end)
game.Players.PlayerAdded:Connect(function(plr)
local stage = plr:WaitForChild("leaderstats"):WaitForChild("Stage")
local datatosave = {}
table.insert(datatosave,1,stage.Value)
data:SetAsync(plr.UserId, datatosave)
end)
@Quwanterz is right, I also wanted to add something on it which is important. You must use pcall() when using GetAsync() and SetAsync(). They can sometimes fail and pcall handles them.
Use pcalls to handle fetching of data and saving of data:
local ds = game:GetService("DataStoreService")
local data = ds:GetDataStore("Data")
game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder",plr)
leaderstats.Name = "leaderstats"
local stage = Instance.new("NumberValue",leaderstats)
stage.Name = "Stage"
local success, plrdata = pcall(function()
return data:GetAsync(plr.UserId)
end)
if plrdata then
stage.Value = table.unpack(plrdata,1,1)
else
stage.Value = 0
end
end)
game.Players.PlayerAdded:Connect(function(plr)
local stage = plr:WaitForChild("leaderstats"):WaitForChild("Stage")
local datatosave = {}
table.insert(datatosave,1,stage.Value)
local success, err = pcall(function()
data:SetAsync(plr.UserId, datatosave)
end)
if not success then print(err) else print("Data saved!") end
end)
I just figured out that I used PlayerAdded instead of PlayerRemoving when I was trying to save the data, lol. Such a simple mistake. Anyways, thanks for all your help guys! I’ll be sure to utilise pcalls now!