Trying to make boombox code work

Okay so I’m trying to make a functional boombox in a house you can place in the sandbox game i’m developing right now and I’m trying to get the script for the play button to choose a random song for the player when pressed. Instead it ends up stating that the value is a userdata value and ends the script right there. Here is the code:
local premusic = script.Parent.Parent.RadioPlay

function onClicked()

print("hopefully its working")

local choose = math.random(1, 2)

local music = premusic("soundy"..choose)

if music.Playing == false then

music.Playing = true

music.Looped = true

else if music.Playing == true then

music.Playing = false

music.Looped = false

music.TimePosition = 0

end

end

end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

If you need a screenshot to better understand where everything is located, here:


any help to solve this issue would be appreciated, thanks.

You can’t get a child of a part with premusic("soundy"..choose)

Instead do local music = premusic:FindFirstChild("soundy" .. math.random(2))

For the audio objects themselves, have the Looped property already true (don’t change it with script). Start and stop the audio with music:Play() and music:Stop().

3 Likes

else if music.Playing == true then is wrong. It’s supposed to be elseif music.Playing then

another way to do this is to actually use math.random for the number of children as well. then from there you can search for the child.

Here is an example:

local premusic = script.Parent.Parent.RadioPlay:GetChildren()
local music = math.random(#premusic)
premusic[music]:Play()

I just feel this is a more efficient way of finding children randomly, but your way works as well.

These are all great solutions, but this creates another problem into the mix. How am I supposed to stop the other music from playing if another one gets chosen in the process to play?

-- Get the song that will play (I needed to make this more efficent than Hello42Bacon lol)
local music = premusic:GetChildren()[math.random(#premusic:GetChildren())]
-- Stop all other songs from playing
for _, song in pairs(premusic:GetChildren()) do
   song:Stop()
end
-- Play the song
music:Play()

use debounce to solve that problem. That way you have a random value set to keep it from playing multiple songs.

local debounce = false

if debounce == false then
    debounce = true
   -- play music until over
    debounce = false
end

or you can use MayorGnarwhal’s way which lets you play different songs whenever you want

This was just what I was looking for. Thanks so much!

1 Like