Attempted to index nil with "Touched"

Hello. I got this error while making a checkpoint script:


Script:

local currentstages = game.Workspace.currentstages
local Players = game:GetService("Players")

local function leaderboardSetup(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local stage = Instance.new("IntValue")
	stage.Name = "Stage"
	stage.Value = 1
	stage.Parent = leaderstats
end

Players.PlayerAdded:Connect(leaderboardSetup)

for _, stages in pairs(game.Workspace.currentstages:GetChildren()) do
	stages:FindFirstChild("CheckPoint", true).Touched:Connect(function()
		local player = game.Players:GetPlayerFromCharacter(stages.SpawnPoint.Parent)
		if player then
			local leaderstats = player:WaitForChild("leaderstats")
			local stage = leaderstats:WaitForChild("Stage")
			if stages.Name == stage.Value - 1 then
				stage.Value = stage.Value + 1
			end
		end
	end)
end

the script cant find a part named CheckPoint inside of currentstages, add a if statement that checks if it exists

if (stages:FindFirstChild("CheckPoint")) then 
--// touched here

Use FindFirstChild in an if statement to ensure that a checkpoint exists for every stage.

local checkpoint = stages:FindFirstChild("CheckPoint", true)
if checkpoint then
	checkpoint.Touched:Connect(function()
		--do stuff
	end)
else
	print("No checkpoint found in stage: "..stages.Name)
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.