Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Choose random brick from a :GetChildren() function?

Asked by
Oficcer_F 207 Moderation Voter
5 years ago

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

Log in to vote
1
Answered by
mattscy 3725 Moderation Voter Community Moderator
5 years ago

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!

0
ITS IMPORTANT THAT THE SEED IS SET FIRST BEFORE USING MATH.RANDOM User#19524 175 — 5y
0
Ok DaggerOf_Fly -24 — 5y
0
I recommend you use the Random type instead, math has a very poor implementation, hence why they added the new Random. gullet 471 — 5y
0
What does math.randomseed(tick()) do? Oficcer_F 207 — 5y
0
@gullet wrong. math.random now follows the same algorithm as Random, but the Random datatype has its own benefits nonetheless User#19524 175 — 5y
Ad

Answer this question