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

A bug in my script i can't seem to understand why it happens, why?

Asked by 4 years ago

in short, i made a script that lets you run when pressing shift, and lets you walk when you let go.

you are able to run when an Intvalue is more than 0, and it increases every second by 1 when not running.

However, if you press shift two times under a second, the intvalue increases by 1 TWICE every second. from my understanding , the script malfunctions and runs the same line twice.

(the main bug starts at line 30)

repeat wait() until game.Players.LocalPlayer
local running = false
local amount = game.StarterGui.run.Value.Value

local function stoprunning()
    game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 11 
end

m = game.Players.LocalPlayer:GetMouse()


m.KeyDown:connect(function(key)
    if key == "0" and running == false then 
        print("Running")
        running = true
        game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 22
        while running == true do
            game.StarterGui.run.Value.Value = math.clamp(game.StarterGui.run.Value.Value - 1, 0, 100)
            local amount = game.StarterGui.run.Value.Value
            print (amount)
            wait(0.1)
            if amount == 0 then
                game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 11
            end
        end

    end
end)

m.KeyUp:connect(function(key)
    if key == "0" and running == true then
        running = false
        local amount = game.StarterGui.run.Value.Value
        game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 11 
        while running == false do
            local amount = game.StarterGui.run.Value.Value
            game.StarterGui.run.Value.Value = math.clamp(game.StarterGui.run.Value.Value + 1, 0, 100)
            print(amount)
            wait(0.9)
        end
    end
end)


0
you have to rewrite your code to use UserInputService instead, Mouse is being Deprecated, Mouse should only be used in Plugins and Tools. Luka_Gaming07 534 — 4y
0
Mouse is NOT being deprecated, but KeyUp/KeyDown are deprecated and UserInputService.InputBegan should be used instead royaltoe 5144 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago

You should always be careful of putting while loops in event handlers: every time someone taps "0" , you start a new while loop, causing your code to run 2x (or more if they keep tapping "0" in the right way).

Two possible fixes:

  • Add additional variables to make sure that you don't enter into the while loops if they're already being run
  • Whenever you start the while loop, increment some variable. Stop executing the loop if this variable is changed (since this means that another thread has started running the while loop and the current thread is now the "old" one).
Ad

Answer this question