Code issues - touched and button click

Hello! I would like to know what is wrong? I want that when I touch the ‘obj’ the button becomes visible and when I stop touching it it is invisible, can someone help me with that, please?

obj.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		button.Visible = true

		button.MouseButton1Click:Connect(function()
			print("button has been touched.")
		end)

	else
		button.Visible = false
	end
end)

image

May I ask what do you mean by obj? Is it like a button? or is it a part in the workplace.

Use TouchEnded to detect when the player has stopped stepping on the part. You should put this into a LocalScript parented to the button as guis should be handled by the client (not the server).

local obj = workspace:WaitForChild("Part")
local button = script.Parent

obj.Touched:Connect(function(hit)
    if hit.Parent == game.Players.LocalPlayer.Character and button.Visible == false then
        button.Visible = true
    end
end)

obj.TouchEnded:Connect(function(hit)
    if hit.Parent == game.Players.LocalPlayer.Character and button.Visible == true then
        button.Visible = false
    end
end)

This might not work as intended since I haven’t actually tested this, but it should be good enough for you to figure out what to do from there.

Edit: In your original code you’re also doing this:

button.MouseButton1Click:Connect(function()
	print("button has been touched.")
end)

On it’s own this is fine, but you’re connecting this function every time the Touched event fires (which can be dozens of times within a single second). This TERRIBLE and will cause the function to fire hundreds of times once its clicked. Place the connection outside of the Touched function and you should be fine.

1 Like