Roblox RemoveEvent 由于某些奇怪的原因触发 2 次

问题描述 投票:0回答:1

我正在制作一个服务器端的 Roblox 代码执行器,但每次我输入“print('Hello World!')”之类的代码时,它都会出于某种原因运行该代码两次。

这是客户端代码:

local textbox = script.Parent
local Attempts = 0
local event = game.ReplicatedStorage.FireCode
local Debounce = false

textbox.FocusLost:Connect(function(enterPressed)
    if enterPressed == true and Debounce ~= true then
        Debounce = true
        repeat
            Attempts += 1
            print(Attempts)
            event:FireServer(textbox.Text)
            task.wait()
        until Attempts == 1
        task.wait(1)
        Attempts = 0
    else
        return
    end
    Debounce = false
end)

这是服务器代码:

local event = game.ReplicatedStorage.FireCode
local debounce = false

event.OnServerEvent:Connect(function(player, code)
    if player and player ~= nil and debounce ~= true then
        debounce = true
        loadstring(tostring(code))()
        task.wait(0.1)
        debounce = false
    end
end)

代码没有错误。

我尝试使用去抖动方法,但没有成功。

lua roblox luau roblox-studio
1个回答
0
投票

不确定为什么要在循环内调用事件,即使该循环应该只执行一次。以下是我处理去抖动事件处理程序的方法。

当游戏运行时,可能值得搜索您的工作空间,看看您是否在某处有此 LocalScript 的克隆。

local textbox = script.Parent
local event = game.ReplicatedStorage.FireCode
local debounce = false
local COOLDOWN = 2.0 -- seconds

textbox.FocusLost:Connect(function(enterPressed)
    -- escape if the flag is active
    if debounce then
       return
    end
    
    if enterPressed then
        debounce = true
        -- get the code and then clear the text box so we don't repeat the same command
        local code = textbox.Text
        textbox.Text = ""

        -- execute the code
        event:FireServer(code)

        -- wait for a moment before clearing the debounce flag
        wait(COOLDOWN)
        debounce = false
    end
end)
© www.soinside.com 2019 - 2024. All rights reserved.