Button scripting help

Hello!

I want to try create a simple script that when a button is pressed a song starts playing (which I know how to do) but I have at least 20+ buttons with 20+ songs but I don’t want to have to put a script inside of every button is there a way I can do this with a single script?

this is the script i currently use which works fine but as said above it has to be inside every single button

local Song = script.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Speaker.Song

function OnClicked() 
	Song.SoundId = "rbxassetid://321540900"
	wait(0.5)
	Song:Play()
end 

script.Parent.MouseButton1Down:connect(OnClicked)

The reason I want it to be inside a single script is so it causes less lag.

2 Likes

You could use TagService, create a tag and add those tags to all the buttons, and then for loop each button that has this tag and you setup the MouseButton1Down event on that button.

put the buttons inside a folder

for i,v in pairs(folder:GetChildren()) do
v.MouseButton1Down:Connect(function()
if v:IsA("TextButton") or v:IsA("ImageButton") then
	Song.SoundId = "rbxassetid://321540900"
	wait(0.5)
	Song:Play()
end 
end
end

i dont have an answer but change your ‘script.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Speaker.Song’ to something simpler like ‘game.Workspace.Song’

Similar to @aquawrsp’s reply put all the textbuttons inside the same parent (folder, gui object, etc.) and have a single script the does the following,

for _, b in pairs(location:GetChildren()) do
    if b:IsA("TextButton") then
        b.MouseButton1Click:Connect(function()
            Song.SoundId = "rbxassetid://"..b.Name -- Make the song id the name of the button (If this isn't optimal let me know)
            wait(0.5)
            Song:Play()
        end)
    end
end

Hope this helps