Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Choose random brick from a :GetChildren() function?

So I want a meteor strike at one of the bricks inside a folder. Then I used a for i,v in pairs loop and a :GetChildren() function, it kinda works. But, I lands in the order the I placed the positions, and not a random. Yes I know in pairs loops go in order, but how can I make it land at a random place? Thanks!

My script so far:

explosion = game.Workspace.Explosions:GetChildren()

for i,v  in pairs(explosion) do

	local part = Instance.new("Part")
	part.Shape = "Ball"
	part.Size = Vector3.new(10,10,10)
	part.BrickColor = BrickColor.new("Burnt Sienna")
	part.Position = Vector3.new(v.Position.X,v.Position.Y+200,v.Position.Z)
	part.Parent = game.Workspace
	wait(1.8)
	local exp = Instance.new("Explosion")
	exp.Parent = game.Workspace
	exp.BlastPressure = 40
	exp.BlastRadius = 120 
	exp.Position = part.Position
	wait(2)
	part:Destroy()
	
end

1 answer

GetChildren() returns a table of the children within the instance that you call the method on. So, to select a random item from this table, you can generate a random number between 1 and the length of the table. You can then index the table with this number to get your random part. For example:

local Explosions = workspace.Explosions:GetChildren()
local ExplosionNumber = math.random(1,#Explosions)
local ChosenExplosion = Explosions[ExplosionNumber]
print(ChosenExplosion,"was chosen")

To make the random number generation different every time, you can add this line at the top of the script too:

math.randomseed(tick())

Hope this helps!

5 comments

0

ITS IMPORTANT THAT THE SEED IS SET FIRST BEFORE USING MATH.RANDOM

0

Ok

0

I recommend you use the Random type instead, math has a very poor implementation, hence why they added the new Random.

0

What does math.randomseed(tick()) do?

0

@gullet wrong. math.random now follows the same algorithm as Random, but the Random datatype has its own benefits nonetheless

This discussion is preserved as it was. New answers, comments, and votes are closed.