I want to play a sound effect when a gui object is clicked and I want to do this with 1 single script in order to prevent lag. I made an very basic script that detects the player’s mouse click event with user input service but it plays the sound without detecting what the object is being clicked and I don’t know how to detect it. Can someone help me with it?
local sounds = game:GetService("ReplicatedStorage"):WaitForChild("Audio"):WaitForChild("UI")
local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
sounds:WaitForChild("UI_ButtonSelect"):Play()
end
end)
They want to make a sound, whenever they click a GUI objects if I read it correctly, and not connect each button itself, and just have one script, that controls this. Try something like this:
local sounds = game:GetService("ReplicatedStorage"):WaitForChild("Audio"):WaitForChild("UI")
local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(input)
local mouse = game.Players.LocalPlayer:GetMouse()
if input.UserInputType == Enum.UserInputType.MouseButton1 and mouse then
local GUI = game.Players.LocalPlayer.PlayerGui:GetGuiObjectsAtPosition(mouse.X, mouse.Y)
local HasClickableObject = false
for i,v in GUI do
if v:IsA("GuiButton") then
HasClickableObject = true
end
end
if HasClickableObject == true then
sounds:WaitForChild("UI_ButtonSelect"):Play()
end
end
end)
Because this works for every GUI button. We aren’t taking about 1 button in my example. we are taking about 10s to 20s of buttons, and if this a GUI heavy game, even more if this is the intended purpose. I am looking at long term effects, not short term. That is what I am assuming unless OP has said anything else
Edit: Title also says “How can i detect when the player’s mouse clicked on a any gui object”, not one object.
Also this means to, if you want to include frames, textlabels etc. as well in my code that I had mentioned above, change: if v:IsA("GuiButton") thentoif v:IsA("GuiBase") then. This will include all GUI elements, and not just buttons like my code did above^