Trouble finding model using math.random

Hello! I am trying to use this script down below to clone a model and put it into workspace. Now I haven’t gotten to cloning yet because each time I try to find the model (In a folder in ServerStorage) with the name chosen by the math.random, it returns with a nil value on line 16.

I have all of the models named correctly as the print statements print(penguinsTable) and print(chosenPenguin) both output the full table and the chosen name from the table.

Script in ServerScriptService
local ss = game:GetService("ServerStorage")
local penguinsFolder = ss:WaitForChild("Penguins")

local penguinsTable = {}

for i, v in pairs(penguinsFolder:GetChildren()) do
	--print(v.Name)
	table.insert(penguinsTable, v)
end

print(penguinsTable)

local function spawnPenguin()
	local chosenPenguin = penguinsTable[math.random(#penguinsTable)]
	print(chosenPenguin)
	local clone = penguinsFolder:FindFirstChild(chosenPenguin) <---- returning a nil value
	print(clone)
	if clone then 
		print(chosenPenguin, " found!")
	end
end

while true do
	wait(2)
	spawnPenguin()
end

What I have tried!

Modified Script
local ss = game:GetService("ServerStorage")
local penguinsFolder = ss:WaitForChild("Penguins")

local penguinsTable = {}

for i, v in pairs(penguinsFolder:GetChildren()) do
	--print(v.Name)
	table.insert(penguinsTable, v)
end

print(penguinsTable)

local function spawnPenguin()
	local chosenPenguin = penguinsTable[math.random(#penguinsTable[1])]
	print(chosenPenguin[1])
	local clone = penguinsFolder:FindFirstChild(chosenPenguin[1]) <---- returns, "[1] is not a valid member of model.
	print(clone)
	if clone then 
		print(chosenPenguin, " found!")
	end
end

while true do
	wait(2)
	spawnPenguin()
end

Thanks in advance!!

Your penguinsTable already contains the penguins, which means penguinsFolder:FindFirstChild(chosenPenguin) is not necessary. It’s also the reason why nil is returned. Furthermore, :FindFirstChild() is a safe way to look for an object’s existence, not a way to clone.

May I suggest the following? (GetChildren() already returns what penguinsTable is expected to contain).

local ServerStorage = game:GetService("ServerStorage")
local penguinsTable = ServerStorage.Penguins:GetChildren()

local RandomGen = Random.new()

local function spawnPenguin()
	local chosenPenguin = penguinsTable[RandomGen:NextInteger(1, #penguinsTable)]
	local clone = chosenPenguin:Clone()
	clone.Parent = workspace
	-- and so on
end

spawnPenguin()

Thank you so much for telling me about the extra table definitions! Definitely wouldn’t have figured that out on my own haha!

1 Like

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