Return value from a table

I’m trying to play a random sound from a table of audios in roblox. I’m a little confused on how to do this though.

wait()
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")

Player.CharacterAdded:Connect(function(Char)
	Character = Char
	Humanoid = Char:WaitForChild("Humanoid")
	HumanoidRootPart = Char:WaitForChild("HumanoidRootPart")
end)

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local SongList = {ReplicatedStorage.KSPSongs.a,ReplicatedStorage.KSPSongs.b,ReplicatedStorage.KSPSongs.c,ReplicatedStorage.KSPSongs.d}

function CheckPlayerHeight(player,height)
	
	local RandomNumber = math.random(1,4)
	
	if player.Position.Y > 20000 then
		
		
	end
end


game:GetService("RunService").RenderStepped:Connect(function()
	CheckPlayerHeight(HumanoidRootPart)
end)

This is my current code. I want to print a number from 1,4 and whatever number that is will play the sound. For example, if I got 2 it would play sound B

2 Likes

If the method to access a field from a table is what you mean then SongList[RandomNumber] should do the trick. Apparently array indexing starts from 1 in lua so you do not need to alter RandomNumber.

Accessing values from a table: Tables | Roblox Creator Documentation

function CheckPlayerHeight(player,height)
	
	local RandomNumber = math.random(1,4)
    print(RandomNumber)
    local RandomSong = SongList[RandomNumber]
	
	if player.Position.Y > 20000 then
		
		
	end
end

GetChildren returns a tabe list of all the children

local SongList = ReplicatedStorage.KSPSongs:GetChildren()
1 Like

This work fine, I’m just stuck on how to get the sound to play for the player. I changed Songlist to KSPSongs:GetChildren(). How do I then clone it, get it to workspace?