Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I go implementing math.random in this script?

The original script is here:

local music = {
	"1839526588",
	"1837871067",
	"4648169560"
}

local music1 = script.Parent.Music
local muted = false

while true do
	for i = 1, #music do
		music1.SoundId = "rbxassetid://"..music[i]
		wait(3)
		music1:Play()
		wait(music1.TimeLength)
	end
end

I have tried to implement math.random into this by doing this:

local music = {
	"1839526588",
	"1837871067",
	"4648169560"
}

local randomMusic = math.random(#music - #music + 1,#music)
local music1 = script.Parent.Music
local muted = false
local ConvertRandomMusicToMusicId = tostring(randomMusic)
local chosenMusic = ConvertRandomMusicToMusicId

while true do
	print(chosenMusic)
	for i = 1, #music do
		music1.SoundId = "rbxassetid://"..chosenMusic[i]
		wait(3)
		music1:Play()
		wait(music1.TimeLength)
	end
end

But it does not seem to work.

Can someone please explain this?

1 answer

✓ Accepted answer

math.random returns a number so the way you're using it is incorrect.

Since your music table has 3 entries, simply pick a number between 1 and 3, and then index the table with it like music[number].

Example:

local music = {
	"1839526588",
	"1837871067",
	"4648169560"
}

local music1 = script.Parent.Music

while true do
	local number = math.random(1, #music) --#music gets the length of the table, in this case 3
	local randomMusic = music[number]
	print(randomMusic)
	music1.SoundId = "rbxassetid://"..chosenMusic[i]
	wait(3)
	music1:Play()
	wait(music1.TimeLength)
end

1 comment

0

Thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.