Code works, but it's erroring

local FinishLine = script.Parent

FinishLine.Touched:Connect(function(otherPart)
	local partParent = otherPart.Parent
    local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")

	local player = game.Players:GetPlayerFromCharacter(partParent)
	local stat = player:WaitForChild('leaderstats'):WaitForChild('Laps')
	
		local bool = game.StarterPlayer:WaitForChild('hasHitCheckpoint')
	if (humanoid and bool.Value == true) then
		stat.Value = stat.Value + 1
		bool.Value = false
	end	
end)

The issue is that the code above returns an “Attempt to index local 'player '(a nil value)” error whenever a player touches FinishLine, as seen in the screenshot below.

Is it possible that I could get rid of these errors? If so, how?

(keep in mind that the code works)

Try changing up this line of code to:

local player = game:GetService(“Players”):GetPlayerFromCharacter(otherPart.Parent)


Nope. Doesn’t resolve the issue…

You need to check if otherPart is a member of the character before setting player.

local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")
if not humanoid then return end
1 Like

The player variable can be nil if anything that is not directly parented to a player’s character touches your finish line, for example, a hat or even an npc. To properly fix your issue you have to guard against the player variable being nil:

if player then
    --- Do stuff
end
1 Like