This code is supposed to make a brick spawn every 10 seconds on a brick spawner (which it is parented under), with a slight chance of being a golden brick, and the brick is given an IntValue. Past bricks are supposed to be deleted.
The two problems I faced:
Multiple bricks spawn at a time
Past bricks are not deleted
Code:
while wait(10) do for i,v in pairs(script.Parent:GetChildren())do if v.Name == "Brick" then v:Destroy() else bval = math.random(1,100) if bval <= 99 then brick = Instance.new("Part", script.Parent) brick.Position = script.Parent.Position brick.Size = Vector3.new(2,0.5,1) brickval = Instance.new("IntValue") brickval.Value = 1 elseif bval == 100 then brick = Instance.new("Part", script.Parent) brick.Position = script.Parent.Position brick.Size = Vector3.new(2,0.5,1) brick.BrickColor = BrickColor.new("New Yeller") sparkles = Instance.new("Sparkles", brick) brickval = Instance.new("IntValue") brickval.Value = 25 end end end end
For the aftermath, the game can be visited here.
(I see you already figured it out, but) the way I'd do it is:
local brick, brickval, bval while wait(10) do if brick then brick:Destroy() end -- Destroy the old part (if any) -- Make a new one brick = Instance.new("Part") brick.Size = Vector3.new(2,0.5,1) brick.Position = script.Parent.Position brickval = Instance.new("IntValue") bval = math.random(1, 100) if bval <= 99 then -- Normal brickval.Value = 1 else -- Golden brick.BrickColor = BrickColor.new("New Yeller") brickval.Value = 25 local sparkles = Instance.new("Sparkles") sparkles.Parent = brick end brickval.Parent = brick brick.Parent = script.Parent end
Do note that Instance.new(part, parent)
is deprecated - you're supposed to do .Parent
after you've changed the other properties (especially Size
and Position
, which cause a bit of unnecessary lag if the part is already in the Workspace). This isn't a concern when you're only making 1 part every 10 seconds, but it's good practice nonetheless.
I changed the structure a bit so that the common code is outside the if
block; you can see exactly what makes a brick normal/golden.