found a way that makes sense to me. i’ll put a reply.
I assume you meant you wanted to set up saving for your leveling system instead and that you were told you’d need a dictionary to save multiple values in it. In that case, you’re on the right track with what you need, but you have code issues.
It would be really helpful if you could identify exactly what line 35 is in this code, since DevForum code samples do not number the code lines meaning we’d have to count it ourselves or open Studio to figure out your exact line of error.
I guess there are a couple of things you’d want to fix up first before that. Two important things:
-
GetGlobalDataStore gets the default DataStore. In production games, you typically never want to use this unless you want to save settings for your entire game. Use GetDataStore instead to create a named DataStore that you can use to store data in.
-
pcall should be used around the DataStore call (GetAsync) alone, not your entire data fetching process. The success value would then be a matter of if the DataStore request successfully went through or not.
Well then… which part is line 35? Have you done some debugging or overviews of your code to understand exactly what went wrong and how you may be able to fix it?
local dss = game:GetService("DataStoreService")
local pd = dss:GetDataStore("PlayerData")
local function onplayerJoin(p)
local stats = Instance.new("Folder")
stats.Name = "leaderstats"
stats.Parent = p
local time = Instance.new("IntValue")
time.Name = "time"
time.Parent = stats
local level = Instance.new("IntValue")
level.Name = "level"
level.Value = 1
level.Parent = stats
local p_userId = 'Player_'..p.UserId
local data = pd:GetAsync(p_userId)
if data then
time.Value = data['time']
level.Value = data['level']
else
time.Value = 0
level.Value = 1
end
end
local function create_table(p)
local p_stats = {}
for _, stats in pairs(p.leaderstats:GetChildren()) do
p_stats[stats.Name] = stats.Value
end
return p_stats
end
local function onplayerExit(p)
local p_stats = create_table(p)
local s, e = pcall(function()
local p_userId = 'Player_'..p.UserId
pd:SetAsync(p_userId, p_stats)
end)
if not s then
warn("Couldd not save data"..p.UserId)
end
end
game.Players.PlayerAdded:Connect(onplayerJoin)
game.Players.PlayerRemoving:Connect(onplayerExit)