How would I make these more complicated Touched events work?

Code Snippet (script is called ButtonScript):

local TS = game:GetService("TweenService")

local function ButtonTouched(Button, Debounce)
	Button:FindFirstChild("Sound"):Play()
        Button:FindFirstChild("Light").Color = Button:FindFirstChild("Inactive").Value
	task.wait(5)
	TS:Create(Button:FindFirstChild("Light"), TweenInfo.new(0.5), {Color = Button:FindFirstChild("Active").Value}):Play()
end

for i, button in ipairs(script.Parent:FindFirstChild("_PressableButtons"):GetChildren()) do
	if button.Name == "Button" and button:IsA("Model") then
		if button:FindFirstChild("Light") and button:FindFirstChild("Hitbox") and button:FindFirstChild("Active") and button:FindFirstChild("Inactive") and button:FindFirstChild("Sound") then
			local Hitbox = button:FindFirstChild("Hitbox")
			Hitbox.Touched:Connect(function(HitPart)
				if HitPart.Parent:FindFirstChildOfClass("Humanoid") then
					ButtonTouched(Hitbox.Parent)
				end
			end)
		end
	end
end

Explorer Snippet (Active and Inactive are Color3 values):
image

I’m trying to make it so that the script will work no matter how many Button models there are in the _PressableButtons folder as long as all the children are the same. However, when I press the button, the sound plays and constantly repeats. The inactive color also fades to active color while I’m standing on it, which makes the color start to act weird as well. I want to make it so that the sound only plays when the color finishes fading back to the “Active” color. How would I make it work?

you might be missing a cooldown for the button (if that would help). because each little character part touches it an fires the function, causing the sound to play many times

Yea, but idk how to add a debounce anywhere in the script. I also don’t know what happens if a function is fired again while it’s running. Another thing I wanted to do is make it so that the buttons change color when touched but also have individual cooldowns (if you get what I mean).

Well you could start off by making a bool value for every button. and inside the function create an if state regarding the debounce

New Function written here:

local function ButtonTouched(Button, Debounce)
if Button.Debounce.Value == false then
    Button.Debounce.Value = true

	Button:FindFirstChild("Sound"):Play()
    Button:FindFirstChild("Light").Color = Button:FindFirstChild("Inactive").Value
	task.wait(5)
	TS:Create(Button:FindFirstChild("Light"), TweenInfo.new(0.5), {Color = Button:FindFirstChild("Active").Value}):Play()

    Button.Debounce.Value = false
end

you can mess with where you put things, but this allows each button to have a cooldown while keeping it in that single function

1 Like

U forgot an “end” at the end, but I’ll try this. Thank you!

oh yeah lol, but im glad i could help!

1 Like