Something wrong with my code

So, I have a script that loops through the StarterGui’s children, and then loops through all the ScreenGuis’s children, and if it found a TextButton instance inside the ScreenGuis, then the sound will play when the TextButton is clicked

Here’s the script but it doesn’t work

local StarterGui = script.Parent
local Sound = StarterGui:WaitForChild("HoverCursorOnAnswerSound")

for i, v in pairs(StarterGui:GetChildren()) do
	if v:IsA("ScreenGui") then
		for index, value in pairs(v:GetChildren()) do
			if value:IsA("TextButton") then
				value.MouseButton1Click:Connect(function()
					Sound:Play()
				end)
			end
		end
	end
end
1 Like

One reason might be that the Sound ID is no longer working, or maybe you set the Volume to 0.
Another reason might be that you used a Script instead of a LocalScript?
While I’m at it, allow me to shorten up your code a bit:

local StarterGui = script.Parent
local Sound = StarterGui:WaitForChild("HoverCursorOnAnswerSound")

for _,textButton in pairs(StarterGui:GetDescendants()) do
   if textButton:IsA("TextButton") then

      textButton.MouseButton1Click:Connect(function()
         Sound:Play()
      end

   end
end

1- I created the Sound like 7 minutes ago

2- The volume is 6

3- I use a LocalScript

4- The script doesn’t work

5- Here’s how my StarterGui look like.

aa

I’m uncertain whether newly created sounds work right away. I believe it can take up to 24 hours for the sound to become fully operational. (Again. Don’t believe me on this.)

Edit: Instead, try a different sound ID first and see if that one plays.

2 Likes

I think I understood why it doesn’t work.

Because I defined the Frame, not its children

EDIT: YES IT’S BECAUSE OF THAT. I edited it and it now works

Also thanks for taking the time to help me:)

Ah yes. You only referenced the Frames, and not the TextButtons themselves.
So the lesson here: Use GetDescendants() instead of GetChildren().

1 Like

When I use GetDescendants, I become unable to use " if v:IsA "

From my testing it was an issue with replication order where the script is cloned first before the GUI. Adding a task.wait() fixed it although I believe there are other better methods such as :WaitForChild() some devs also prefer cloning GUI from replicated storage to avoid wait for child.

image

local StarterGui = script.Parent
--local Sound = StarterGui:WaitForChild("HoverCursorOnAnswerSound")
print(StarterGui)
print("Before Wait")
print(StarterGui:GetChildren())
task.wait()
print("After Wait")
print(StarterGui:GetChildren())
for i, v in pairs(StarterGui:GetChildren()) do
	if v:IsA("ScreenGui") then
		for index, value in pairs(v:GetChildren()) do
			if value:IsA("TextButton") then
				print("Text button found", value)
				value.MouseButton1Click:Connect(function()
					print("Clicked")
					--Sound:Play()
				end)
			end
		end
	end
end

image

1 Like