How to use math.random for instances inside a folder

Hey! So im making a tower defense game and im working on a lobby music system that randomly switches every time another one ends, and im kinda having a problem bc i never did this before

Can anyone help me?

2 Likes

Where is the script placed? / Show me the script and the Folder

Here is some code that should work.

local MusicFolder = -- folder

local function ChooseMusic()
  local ChosenIndex = math.random(1, #MusicFolder:GetChildren())
  local ChosenMusic = MusicFolder[ChosenIndex]
  return ChosenMusic
end

edit: realised it was about music

2 Likes
local MapsFolder = -- folder

local function ChooseMap()
  local ChosenMap = MapsFolder[math.random(1, #MapsFolder:GetChildren())]
  return ChosenMap
end

modified

1 Like
local MFolder = -- // Insert folder name here

MFolder[math.random(1, #MFolder)]:Play()
-- // Or 
MFolder[math.random(1, #MFolder:GetChildren())]:Play()

-- // Or

MFolder[math.random(1, #MFolder):Play()]

-- // Wasn't coding this for long time
1 Like
local Folder = script.MusicFolder --folder path

function getRandomSong()
	local songs = Folder:GetChildren()
	local index = math.random(1, #songs)
	return songs[index] 
end)

local chosen = getRandomSong()
print(chosen.Name, chosen.SoundId)

If you want to avoid duplicates in a row, you may want to use a chances system:

local Folder = script.MusicFolder

local chances = {}

function IncreaseChances()
	for _, song in pairs(Folder:GetChildren()) do 
		if not chances[song] then 
			chances[song] = 0 
		end
		chances[song] += 1
	end
end

function ConvertChancesToArray()
	local array = {}
	for song, chance in pairs(chances) do 
		for i = 1, chance do 
			table.insert(array, song)
		end
	end
	return array 
end

function PickSong()
	local array = ConvertChancesToArray()
	local chosen = array[math.random(1, #array)] 
	IncreaseChances()
	chances[chosen] = 0
	return chosen 
end

IncreaseChances()

--wont pick the same song twice in a row, the chances increase when a song hasn't been played for a long time.
while task.wait(.1) do 
	local song = PickSong()
	print(song.Name, song.SoundId)
end 
3 Likes

Thx for the help! this also helped to make other systems!

Thx for the help! But its only lobby musics and not for the maps

Thx! This helped me to understand more about it!

Yooo thx i needed this! ima mark your response as solution cuz i also needed that system!

1 Like

then change it to music