Having trouble with picking an random object in a folder

so the problem i’m having here is that i wan’t to make a script select two random objects within a folder and there are two folders because they are different categories of items. items that infect you or items that are used as weapons. then after that it’ll pick 1 out of the 2 then spawn that item.

Anyway here is the line:

ChosenItem = ToolList[math.random(1, #ToolList)]:Clone()

if you need the full function tell me!

1 Like

Can you please send the full function and are there any errors?

Make sure tool list is a table. If it is in a folder, you can do:

local folder = game.Workspace:FindFirstChild("folder") -- replace with your path
local ToolList = folder:GetChildren();

ChosenItem = ToolList[math.random(1, #ToolList)]:Clone()

Are the names of the tools numbers? Cause if it picks a number like for example 1, you script will try to clone a tool called 1

i didd that already also yes there is a error so lemme send two things that were requested (i forgot to send the error)

error:

 Workspace.Folders.Important folders.MapPreMades.Special.ItemSpawner.ItemSpawnerScript:14: invalid argument #2 to 'random' (interval is empty)

full function:

local function chooseRandomItem()
	local ItemType = math.random(1,2)
	if ItemType == 1 then
	local ToolList = Tools:GetChildren()
	ChosenItem = ToolList[math.random(1, #ToolList)]:Clone()
	elseif ItemType ==  2 then
	local InfectingList = Tools:GetChildren()
		ChosenInfectingItem = InfectingList[math.random(1, #InfectingList)]:Clone()
	end
end

For some reason, your script gets that #InfectingList or #ToolList is nil.
Are these folders the correct ones? And do they have tools in them?

Actually it means the one of those tables is empty

1 Like

Here, this code works:

local ToolList = game:GetService("ReplicatedStorage"):FindFirstChild("ToolList")

local function pickRandomTool(m : number): Instance
	m = m or 1
	local Tools = ToolList:GetChildren()
	local toolsTable = {}
	for k,v in pairs(Tools) do
		table.insert(toolsTable, v)
	end
	return toolsTable[math.random(m, #toolsTable)]
end

local RandomTool = pickRandomTool(1):Clone()

It inserts each item under the tool folder into the toolsTable, then picks a random item from it when fired. (ik, a bit hacky, but I tested it and it works.)

i think that is the problem, woops

so now there is another erorr i have which i also need help with

What is the error you are talking about?