Why isn't this table working?

My goal for this script is so that it will pick a random song from the table from a folder inside of ServerStorage using math.random but when I try it, it spits out this error: attempt to index nil with 'SoundId'
I think the sounds I put inside of ServerStorage ARE sounds
Script:

local MusicFolder = game:GetService("ServerStorage").Music

local songs = {
	TheGreatStrategy = MusicFolder:FindFirstChild("TheGreatStrategy"), 
	Candyland = MusicFolder:FindFirstChild("Candyland"),
	Gaiety = MusicFolder:FindFirstChild("Gaiety")
}

wait(1)

local PlayerSound = Instance.new("Sound")
PlayerSound.Parent = game.Workspace
PlayerSound.Name = "SOUNDPLAYER"

while true do
	local currentsong = songs[math.random(1, 3)]
	local playingsong = currentsong.SoundId
	wait(3)
	PlayerSound.SoundId = playingsong
	PlayerSound:Play()
	task.wait(PlayerSound.TimeLength)
end
2 Likes

It’s because you set the index for the table a name instead of a number, so math.random(1,3) is not finding any and returns as nil.

Try making the table something like this.

local songs = {
    [1] = {
        ["Name"] = "TheGreatStrategy",
        ["Sound"] = MusicFolder:FindFirstChild("TheGreatStrategy"),
    },
    [2] = {
        ["Name"] = "Candyland",
        ["Sound"] = MusicFolder:FindFirstChild("Candyland"),
    },
    [3] = {
        ["Name"] = "Gaiety",
        ["Sound"] = MusicFolder:FindFirstChild("Gaiety"),
    },
}

local RandomSong = songs[math.random(1, #songs)]
local SoundId = RandomSong["Sound"].SoundId

Or you wouldn’t even need the table in the first place, you could also do this.

local songs = MusicFolder:GetChildren()

local RandomSound = songs[math.random(1,#songs)]
local SoundName = RandomSound.Name
local SoundId = RandomSound.SoundId

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.