Search code examples
lua3droblox

how should I fix While True loop repeating and stopping unwantedly (Roblox)


I am trying to make a part duplicate then delete the duplication script with the new part without deleting the script in the old part, this is in Roblox studio.

This is my code

local block = script.Parent


while true do
    local xrange = math.random(-250,250)
    local zrange = math.random(-250,250)
    local item = block:Clone()
    item.Parent = game.Workspace
    item.Position = Vector3.new(xrange,.5,zrange)
    item["Block Script"]:Destroy()
    game.ReplicatedStorage.ItemCount.Value = game.ReplicatedStorage.ItemCount.Value + 1
    wait(1)
end

The problem is that it runs as if it is supposed to duplicate 3 times for every loop and rather than creating 1 new part each second, it creates 3 parts. The main issue is that sometimes 1 of the 3 new parts won't have the other script that I have inside the parts, making the part a useless part that causes problems.

Does anyone see a problem? You can also comment if you want more clarification.

If this is just an error or cannot be solved through the information given, I can probably work around but please comment if you need my clarification


Solution

  • Its duplicating 3 times because you are destroying the script last.. what you should try doing is:

    1- creating a new folder on workspace ( going to call it "blocks" for example )

    2- making the block and script of the block as the children of the "blocks" folder

    3- and placing this code on the script:

    local block = game.workspace."**blocks**".(Your part name)
    
    
    while true do
        local xrange = math.random(-250,250)
        local zrange = math.random(-250,250)
        local item = block:Clone()
        item.Parent = game.Workspace
        item.Position = Vector3.new(xrange,.5,zrange)
        game.ReplicatedStorage.ItemCount.Value = game.ReplicatedStorage.ItemCount.Value + 1
        wait(1)
    end
    

    If this does not work you can reply to this comment.