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

Random Brick spawning script?

Asked by 9 years ago

I made this script and what it does is spawns different sized blocks at different positions and is different colors. I want it to make blocks every 0.3 seconds and then delete the blocks that are in the workspace for 2 seconds, but instead it's making blocks every 2 seconds and deleting them every 2 seconds, help.

while true do
    wait(0.3)
p=Instance.new("Part",game.Workspace)
p.Size=Vector3.new(math.random(1,10),math.random(1,10),math.random(1,10))
p.Position=Vector3.new((math.random(-50,50)),50,(math.random(-50,50)))
p.Color=Color3.new(math.random(),math.random(),math.random())
wait(2)
p:remove()
end

2 answers

Log in to vote
1
Answered by 9 years ago
while true do
    wait(0.3)
p=Instance.new("Part",game.Workspace)
p.Size=Vector3.new(math.random(1,10),math.random(1,10),math.random(1,10))
p.Position=Vector3.new((math.random(-50,50)),50,(math.random(-50,50)))
p.Color=Color3.new(math.random(),math.random(),math.random())
game.Debris:AddItem(p,2) -- Using game.Debris:AddItem(), we remove p in 2 seconds without delaying the script.
end

0
Thanks so much! QuantumScripter 48 — 9y
Ad
Log in to vote
1
Answered by
Redbullusa 1580 Moderation Voter
9 years ago

Either you need to use multi-thread functions, like a coroutine or spawn, or use the debris service.

Using the Debris service.

-- I separated the code so you could see what is going on easier.

function MakePart()
    local Part = Instance.new("Part",game.Workspace)
    Part.Size = Vector3.new(math.random(1,10),math.random(1,10),math.random(1,10))
    Part.Position = Vector3.new((math.random(-50,50)),50,(math.random(-50,50)))
    Part.Color = Color3.new(math.random(),math.random(),math.random())
    return Part
end

while true do
    wait(.3)
    local p = MakePart()
    game:GetService("Debris"):AddItem(p, 2)
end

Using spawn.

-- I felt like "spawn" is the most appropriate way out of spawn & coroutines.

function MakePart()
    local Part = Instance.new("Part",game.Workspace)
    Part.Size = Vector3.new(math.random(1,10),math.random(1,10),math.random(1,10))
    Part.Position = Vector3.new((math.random(-50,50)),50,(math.random(-50,50)))
    Part.Color = Color3.new(math.random(),math.random(),math.random())
    return Part
end

function DestroyItem(Instance, Time)
    wait(Time)
    if Instance then -- Making sure this thing isn't destroyed before the Destroy method runs. ;)
        Instance:Destroy()
    end
end

while true do
    wait(.3)
    local p = MakePart()
    spawn(function()
        DestroyItem(p, 2)
    end)
end

I'm kind of in favor with the spawn function, because according to "Notes" in this link, the AddItem function in the Debris service removes instances like the Remove method does (a deprecated method of removing things).

Answer this question