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

Is there a while loop alternative?

Asked by 6 years ago

The following code checks ever 0.5 seconds to see if the SelectedSlot has a Y position of 0, 0. If it does, then all tools currently equipped by the player will be unequipped.

However this crashes my game. I have a feeling that this while loop is the reason.

while true do
    if SelectedSlot ~= nil then
        ScaleX = SelectedSlot.Position.X.Scale
        OffsetX = SelectedSlot.Position.X.Offset
        ScaleY = SelectedSlot.Position.Y.Scale
        OffsetY = SelectedSlot.Position.Y.Offset
        if OffsetY == 0 then
            Player.Character.Humanoid:UnequipTools()
        end
        wait(0.5)
    end
end

Any solutions to make this loop work or alternatives that will serve the same purpose? Thanks in advance.

1
its not really a good idea to rely on the gui position to run code, you should do this upon the users action / event. User#5423 17 — 6y
0
You should use :GetPropertyChangedSignal (http://wiki.roblox.com/index.php?title=API:Class/Instance/GetPropertyChangedSignal) instead. Also, the reason it's freezing is you only wait if the condition is true. You should move the wait outside of the if statement. GoldenPhysics 474 — 6y
0
idk WaitForChild() since it yields Araknala 14 — 6y

1 answer

Log in to vote
1
Answered by 6 years ago

There are two solutions instead of using while true do. You could use RenderStepped, which is basically wait(0.000001), or you can use while wait() do.

while wait() do
--do something
end
game:GetService("RunService").RenderStepped:Connect(function()
    --do something
end)

I think adding a wait() makes a big difference as it doesn't crash your game as easily. Please accept my answer if this helped! If it didn't, please comment! Thanks!

0
Renderstepped is actually 1/60th of a second, meaning it is more around 0.01666(repeating) User#9949 0 — 6y
0
Oh. PyccknnXakep 1225 — 6y
Ad

Answer this question