Need help to fix this script

So i was watching a video that shows you how to make an obby system with checkpoints that saves your stages but when i reset or leave the server it just makes me respawn on the SpawnLocation but it still saves the stage number in the leaderboards.

Here is the script I used
local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local saveDataStore = dataStoreService:GetDataStore("SaveDataTest")

local function savePlrData(plr)
	
	local success,err =	pcall(function()
		
		local saveData = {}
		
		for _,stat in pairs(plr.Leaderstats:GetChildren()) do
			
			saveData[stat.Name] = stat.Value
			
		end
		
		saveDataStore:SetAsync(plr.UserId,saveData)
	
	end)
	
	if not success then return err end
	
end

players.PlayerAdded:connect(function(plr)
	
	local stats = Instance.new("Folder")
	stats.Name = "leaderstats"
	stats.Parent = plr
	
	local stage = Instance.new("IntValue")
	stage.Name = "Stage"
	stage.Parent = stats
	
	local data = saveDataStore:GetAsync(plr.UserId)
		
	if data then
		
		print(data.Stage)
		
		for _,stat in pairs(stats:GetChildren()) do
			
			stat.Value = data[stat.Name]
			
		end
		
	else
		
		print(plr.Name .. " has no data")
		
	end
	
	plr.CharacterAdded:connect(function(char)
		
		local humanoid,hrp = char:WaitForChild("Humanoid"),char:WaitForChild("HumanoidRootPart")
		
		wait()
		
		if humanoid and hrp then
			
			if stage.Value == 1 then
				
				local part = workspace.ObbyStages:FindFirstChild(stage.Value)
				hrp.CFrame = part.CFrame + Vector3.new(0, 1, 0)
				
			end
			
		end
		
	end)
	
end)

players.PlayerRemoving:connect(function(plr)
	
	local err = savePlrData(plr)
	
	if err then print(err) end
	
end)

game:BindToClose(function()
	
	for _,plr in pairs(players:GetPlayers()) do
		
		local err = savePlrData(plr)
	
		if err then print(err) end
	
	end
	
	wait(2)
	
end)
Here is what the output says

Leaderstats is not a valid member of Player

By the way I am still new to scripting so sorry for the mistakes ¯_(ツ)_/¯

You’re trying to get Leaderstats as a child of player but it is actually called leaderstats. Caps matters.

Use plr.leaderstats instead.

1 Like

As it’s not automatically made, if you didn’t make leaderstats, this error would be thrown. Also, @Nucl3arPlays’ answer is accurate.

Leaderstats is made for the player when the player joins. It only saves when the player leaves so I don’t really know what you’re on about. Unless the player leaves two milliseconds after the player joins then it’ll be fine.

I am an idiot. I didn’t see your code. Alright, sorry.