Why am I getting error "attempt to index nil with 'Clone'"

Why am I getting the error “attempt to index nil with ‘Clone’”? Inside the function, all the values are assigned, but for some reason, when running the script it randomly throws this error. I don’t know what it is because, to my knowledge, it’s not tied to rarities or a specific number.

Here is my script that is running on the server:

local spawner = workspace.PartSpawn
local prompt = script.Parent

local size = {max = 10, min = 3}
local color = {max = 255, min = 0}

local typesFolder = game.ReplicatedStorage.BlockTypes

types = {
	["Legendary"] = typesFolder:FindFirstChild("Legendary"),
	["Epic"] = typesFolder:FindFirstChild("Epic"),
	["Rare"] = typesFolder:FindFirstChild("Rare"),
	["Uncommon"] = typesFolder:FindFirstChild("Uncommon")
}

rarities = {
	["Legendary"] = 1,
	["Epic"] = 10,
	["Rare"] = 25,
	["Uncommon"] = 50
}

function ChooseRandomPart()
	local rand = math.random(1, 100)
	local counter = 0

	for rarity, weight in rarities do
		counter += weight
		if rand <= counter then
			print("number:", rand, "rarity:", rarity)
			return types[rarity]
		end
	end
end

while task.wait(.05) do
	local part  = ChooseRandomPart():Clone()
	
	part.Position = spawner.Position
	part.Parent = spawner.SpawnedParts
	part.Size = Vector3.new(math.random(size.min, size.max), math.random(size.min, size.max), math.random(size.min, size.max))
	part.Color = Color3.new(math.random(color.min, color.max), math.random(color.min, color.max), math.random(color.min, color.max))
end

Because ChooseRandomPart returns nil if rand > counter for all rarities.

1 Like

Thanks, I didn’t realize my rarities didn’t sum to 100

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