How Do I Fix This Collection Service Script

  1. What do you want to achieve? Keep it simple and clear!
    I want every text button with the buttonclick tag the play a sound on MouseButton1Down.

  2. What is the issue? Include screenshots / videos if possible!
    The script does not work. there are no error messages

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried using chat gpt but that has not worked.

-- local CollectionService = game:GetService("CollectionService")

-- Define the tag you want to use
local buttonClickTag = "ButtonClick"

-- Function to handle button click
local function handleButtonClick()
	game:GetService("SoundService").Click:Play()
end

-- Iterate over instances with the "ButtonClick" tag
for _, button in ipairs(CollectionService:GetTagged(buttonClickTag)) do
	if button:IsA("TextButton") then
		button.MouseButton1Down:Connect(handleButtonClick)
	end
end

It doesn’t look like anything is wrong with it
Try adding prints after each line of code to find what is running and what is not

I like to make a function called “HookUpThing” that would be like this code:

function HookUpButtonClickSound(button)
	if button:IsA("TextButton") then
		button.MouseButton1Down:Connect(handleButtonClick)
	end
end

Then I run the hookup function for all existing objects with the tag like you do:

for _, button in ipairs(CollectionService:GetTagged(buttonClickTag)) do
	HookUpButtonClickSound(button)
end

But then I’d also listen for instances with tag being added, incase the script runs before the instances exist.

CollectionService:GetInstanceAddedSignal(buttonClickTag):Connect(HookUpButtonClickSound)

Thanks for they help! This worked perfectly.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.