Hello! I am having some issues to save leaderstats value. For some reason, it fails to save.
local Players = game:GetService("Players")
local LS = Instance.new("Folder")
local DS = game:GetService("DataStoreService")
local DataStore = DS:GetDataStore("DataStore1")
Players.PlayerAdded:Connect(function(plr)
local LS = Instance.new("Folder")
LS.Name = "leaderstats"
LS.Parent = plr
local Level = Instance.new("IntValue")
Level.Parent = LS
Level.Name = "Level"
Level.Value = DataStore:GetAsync(plr.UserId)
pcall(function(success, errorMessage)
DataStore:SetAsync(tostring(plr.UserId), {
Level.Value
}, plr.UserId)
if success then
print("Called succesfully!")
else
warn(errorMessage)
end
end)
end)
Players.PlayerRemoving:Connect(function(plr)
local LS = plr:FindFirstChild("leaderstats")
pcall(function(success, errorMessage)
DataStore:SetAsync(plr.UserId, {
LS.Level.Value
}, plr.UserId)
if success then
print(success)
else
print(errorMessage)
end
end)
end)
Man . That is a really messy script . Anyways I have fix some parts for you . Hope it works lol
PS im on mobile
local Players = game:GetService("Players")
local LS = Instance.new("Folder")
local DS = game:GetService("DataStoreService")
local DataStore = DS:GetDataStore("DataStore1")
Players.PlayerAdded:Connect(function(plr)
local LS = Instance.new("Folder")
LS.Name = "leaderstats"
LS.Parent = plr
local Level = Instance.new("IntValue")
Level.Parent = LS
Level.Name = "Level"
Level.Value = 0 -- Set it to level for new players
local Data = DataStore:GetAsync(plr.UserId) -- Data would look something like {Level = x} since this is how we set it when the player leave
if Data then --check if the player have a valid data
if Data.Level then--Just an extra check to prevent errors if the player does not have a saved value for any reason
Level = Data.Level
end
end
--//There is no need for this line since the data save when the player is leaving anyways
--pcall(function(success, errorMessage)
-- DataStore:SetAsync(tostring(plr.UserId), {
-- Level.Value
-- }, plr.UserId)
-- if success then
-- print("Called succesfully!")
-- else
-- warn(errorMessage)
-- end
--end)
end)
Players.PlayerRemoving:Connect(function(plr)
local LS = plr:FindFirstChild("leaderstats")
local suc ,err = pcall(function()
local SaveData = {}
SaveData.Level = LS.Level.Value -- SaveData.Level basically set the index(assume it is like a name of a property) to the value of "leaderstats.Level.Value"
DataStore:SetAsync(plr.UserId,SaveData,plr.UserId)
end)
if err then
warn(err)
end
end)
basically some errors that might happen is that if the player have no saved data, the data would be nil and setting a value to nil will throw an error . Another problem there is that when he player leave, you set the value to a table {} . Setting value to a table will also throw an error