Script work fine but sometimes having an error saying "attempt to index nil with 'findfirstchild' "

  1. What do you want to achieve? Keep it simple and clear!
    I’m making a points system

  2. What is the issue? Include screenshots / videos if possible!
    It works fine but sometimes having an error saying "attempt to index nil with ‘findfirstchild’ "

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Searching but still got no idea why

script.Parent.Touched:Connect(function(hit)
    if deb == false then
        local ply = players:GetPlayerFromCharacter(hit.Parent)

        local Bricks = ply:FindFirstChild("Bricks")
        local Gifts = ply:FindFirstChild("Gifts")

        if Bricks.Value >= 5 then
            deb = true
            Bricks.Value = Bricks.Value - 5
            Gifts.Value = Gifts.Value + 1
            wait(0.2)
            deb = false
        end
    end
end)

Try with “:WaitForChild(’ ')” or with hit.Parent (If the Bricks.Value is on the players Character)

it’s because sometimes it collides with other objects too and not a player, and that object may have no parent

so it would return a nil when you are trying to find a child of it

add something that will check if the part is hitting a player before Getting the player from the character
example:

if hit and hit.Parent and hit.Parent:FindFirstChild("Humanoid")
    --your code
end
local players = game:GetService("Players")
local part = script.Parent
local deb = false

part.Touched:Connect(function(hit)
	if deb == false then
		local ply = players:GetPlayerFromCharacter(hit.Parent)
		if ply then
			local Bricks = ply:FindFirstChild("Bricks")
			local Gifts = ply:FindFirstChild("Gifts")
			if Bricks and Gifts then
				if Bricks.Value >= 5 then
					deb = true
					Bricks.Value -= 5
					Gifts.Value += 1
				end
			end
		end
	end
	task.wait(0.2)
	deb = false
end)

Just some minor improvements to what has already been suggested. I’ve replaced wait() with task.wait(), shortened the arithmetic operations and applied the necessary fixes to the script as a whole.