Help With a Touch event

Hello,
I am am creating a mystery box that when ever a player touches it, it loops through the images stored inside a table and assigns it to the Gui image.

The issue is that sometimes it works and other times it does not as you can see from the code below i have two print statement one inside the begging block of the function “mystery.Random” and another
after it has detected the Humanoid. Sometime it works as intended but other times it does not work
and does not seem to detect the humanoid.

I have tried Using the waitforchild function but its the same result, can anyone explain why ?

function Mystery.random(hit,p)
	p:Destroy()
	print("we here 1 ")
	if hit.Parent:FindFirstChild("Humanoid") then
		print("we here 2 ")
		local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
		Player.PlayerGui.MysteryGui.Enabled = true
		if Player then
			for i = 1,#ImagesId do 
				Player.PlayerGui.MysteryGui.ImageLabel.Image = ImagesId[i]
				task.wait(0.8)
			end
		end
		PowerUps(hit.Parent,Player)
		
	end
	
end


for i,p in ipairs(game.Workspace.Mystery:GetChildren()) do 
	p.Touched:Connect(function(hit)
		Mystery.random(hit,p)
	end)
	
end

return Mystery

This is a Module Script

1 Like

Do you get any errors? char(30)

No errors at all, it works sometimes other times it does not.

Maybe add a debounce? The script might not be able to keep up or something.

I think I found the problem if u see from the image, that when I would jump on the part from below it would detect the Handle part and the parent of that is the pal hair not the Main Character Model.
Does anyone know the best way to solve this ?

Maybe by adding this to check if the touching object is a part of a character:

local character = hit:FindFirstAncestorOfClass(“Model”)
if not character then return end
local humanoid = character:FindFirstChild(“Humanoid”)
if not humanoid then return end

Thanks For everyone’s help The FindFirstAncestorOfClass function helped.