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

My script prints multiple times when it's touched, and it should only once per touch. How to fix?

Asked by 2 years ago

Here's an example:

Player = 0

while task.wait() do
    local Zone = workspace:GetPartsInPart(script.Parent)
    for i, v in pairs(Zone) do
        if v.Name == "UpperTorso" then
            wait()
                Player = 1
        end
    end
    if Player == 1 then
        print("player do exist")
        OpenAnim:Play()
        wait(0.71)
        OpenAnim:AdjustSpeed(0)
        Player = 2
    elseif Player == 2 then
        Player = 0
        OpenAnim:AdjustSpeed(1)
        print("Player dont exist")
    end
    end

Every time my character overlaps with the script parent, OpenAnim loops when it should just play once per interaction and freeze.

1 answer

Log in to vote
0
Answered by 2 years ago

The code is in a loop, so it repeatedly runs through the code many times per second. In this case, as long as Player is equal to one it will loop as many times as it can before Player == 2. I would add debounce argument to your if statement. Try what I have written below. I'm not sure if it will work in the context of your code but hopefully it gives you an idea. I hope this helps!

Player = 0
local debounce = true

while task.wait() do
    local Zone = workspace:GetPartsInPart(script.Parent)
    for i, v in pairs(Zone) do
        if v.Name == "UpperTorso" then
            wait()
            Player = 1
        end
    end
    if Player == 1 and debounce == true then
        print("player do exist")
        OpenAnim:Play()
        debounce = false
        wait(0.71)
        debounce = true
        OpenAnim:AdjustSpeed(0)
        Player = 2
    elseif Player == 2 and debounce == true then
        Player = 0
        OpenAnim:AdjustSpeed(1)
        print("Player dont exist")
    end
end

Ad

Answer this question