Spawning Random Cubes from a Folder with Rarity

I’m trying to make a part that spawns a random cube from a folder. I’m having some trouble figuring out how I would do that. I’d also like to be able to control the chances of certain cubes spawning.

local spawnerPart = script.Parent

local cubes = workspace.Cubes.Basic

local maxCubes = 10
local spawnedCubes = 0

while true do
	if spawnedCubes < maxCubes then
		--Spawn the Cubes
		spawnedCubes += 1
	elseif spawnedCubes == maxCubes then
		print("Max Cubes")
		wait(3)
	end
end

Sorry wasn’t sure if that was the problem or not …
Here is a quicky. Keys off the size of the “spawner”
Tried to use your code a bit. Or atleast match up to it.

task.wait(3)

local cube = workspace.Cubes.Basic.Cube
local spawner = script.Parent
local sX = spawner.Size.X
local sZ = spawner.Size.Z
local sY = spawner.Position.Y + 
	spawner.Size.Y /2 + cube.Size.Y /2
local pause = 1

function SpawnArea()
	local X = math.random(-sX /2, sX /2)
	local Z = math.random(-sZ /2, sZ /2)
	local spot = Vector3.new(X, sY, Z)
	return spot
end

function PlaceCube()
	local clone = cube:Clone()
	local spot = SpawnArea()
	clone.Parent = workspace
	clone.Position = spot
	task.wait(pause)
end

local maxCubes = 10
local spawnedCubes = 0

while true do
	if spawnedCubes < maxCubes then
		
		PlaceCube()
		spawnedCubes += 1
		if spawnedCubes == maxCubes then 
			break
		end
	end
end

print(spawnedCubes)

Drop this script in the baseplate, set the pause to 0.01 and the maxCubes to 500. :slight_smile: (for testing).

Thanks for clearing that up, but my main issue is the spawning the actual cubes. Any idea how I could do that?

1 Like

To select something in a weighted-random fashion you just need to map a randomly selected number’s range on to a list of possible cubes. math.random() returns a value between 0.0 and 1.0. If you want one cube to have a 10% chance and another cube to have 90% chance, then a value between 0.0 and 0.1 should spawn the rare cube and values over 0.1 should spawn the common cube.

So how I would select a child of the folder to spawn in? I don’t think that GetChildren would work in this case, so I’m not sure how I could get the children of the folder and select one randomly

Make the selection in your code then look up the cube model using its name. You could have a table like this:

local chances = {
	["rareCube"] = 0.1,
	["commonCube"] = 0.9,
}

local function SelectCube()
	local r = math.random()

	for cubetype, chance in pairs(chances) do
		r -= chance
		if r <= 0 then
			return cubetype
		end
	end
end

local cubeToSpawn = CubeFolder[SelectCube()]:Clone()

Use a random.new():nextnumber(chance), This will make it more accurate. And for tables, use ipairs instead of pairs

The order the table is iterated does not matter in this implementation. I’m not familiar with nextnumber().