You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何断开UIS.InputBegan:Connect(...)绑定的函数?代码重复执行失败求解

问题分析与解决办法

你这代码的问题在于每次点按钮都会重复绑定UIS.InputBegan事件——第一次点完绑定的事件没移除,后面再点就会叠加好几个监听,KSIO的状态判断直接乱套,所以第二次执行就失效了。

当然能断开这个绑定,Connect()方法会返回一个RBXScriptConnection对象,把这个对象存起来,要断开的时候调用它的Disconnect()方法就行。

给你改好的代码示例:

local inputConnection -- 用来保存事件连接对象

script.Parent.MouseButton1Down:Connect(function()
    -- 如果之前有未断开的连接,先清理掉
    if inputConnection then
        inputConnection:Disconnect()
        inputConnection = nil
    end

    KS.Visible = true
    KSIO = true
    wait(.5)
    
    -- 保存新的事件连接对象
    inputConnection = UIS.InputBegan:Connect(function(Input, gameProcessedEvent)
        if KSIO == true then
            script.Parent.Text = Input.KeyCode.Name
            KS.Visible = false
            KSIO = false
            -- 输入完成后主动断开连接,避免残留监听
            inputConnection:Disconnect()
            inputConnection = nil
        end
        print(KSIO)
    end)
end)

还有个更省心的写法:只绑定一次InputBegan事件,用状态变量控制是否响应输入,不用反复断开连接:

local isListening = false

-- 只绑定一次事件,避免重复叠加
UIS.InputBegan:Connect(function(Input, gameProcessedEvent)
    if isListening then
        script.Parent.Text = Input.KeyCode.Name
        KS.Visible = false
        isListening = false
    end
    print(isListening)
end)

script.Parent.MouseButton1Down:Connect(function()
    KS.Visible = true
    isListening = true
    wait(.5)
end)

这样不管点击多少次按钮,都只有一个事件监听,逻辑更清晰,也不会出现重复绑定导致的失效问题。

内容的提问来源于stack exchange,提问作者MMT007_backUP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:06:33