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:
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().
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()