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

What is wrong with my script?

Asked by
xApRix 25
9 years ago

Please make your question title relevant to your question content. It should be a one-sentence summary in question form.

I have my script set up where a loop is resumed when the player is walking and is paused while the player is stopped. When I run the script it runs correctly for the first time, but after that the loop seems to not work. Does anyone know what is wrong with my script?

local Camera = workspace.CurrentCamera
local Player = game.Players.LocalPlayer
local Figure = Player.Character
local Mouse = Player:GetMouse()

local i = 0
local W = false

CamMovment = coroutine.create(function()
    while W == true do 
        wait()
        print(i)
        i = i + 1
    end
end)

Mouse.KeyDown:connect(function(key)
    if key == "w" then
        W = true
        coroutine.resume(CamMovment)
    end
end)

Mouse.KeyUp:connect(function(key)
    if key == "w" then
        W = false
        coroutine.yield(CamMovment)
    end
end)

1 answer

Log in to vote
2
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
9 years ago

The coroutine is a separate thread. The while loop is in that thread. When W is set to false, the while loop stops. Resuming the thread does not reboot it. Here's something better you can do:

local Camera = workspace.CurrentCamera
local Player = game.Players.LocalPlayer
local Figure = Player.Character
local Mouse = Player:GetMouse()

local i = 0
local W = false

Mouse.KeyDown:connect(function(key)
    if key == "w" then
        W = true
        while W do
            wait()
            print(i)
            i=i+1
        end
    end
end)

Mouse.KeyUp:connect(function(key)
    if key == "w" then
        W = false
    end
end)

You don't need a coroutine.

Ad

Answer this question