我在 Roblox 中的脚本运行良好,但是一旦我添加了去抖动,它仍然运行良好,但只是有时?

My script in Roblox works fine, but once I added a debounce, it still worked perfectly, but only sometimes?

例如:脚本在一个游戏会话中运行良好,但在另一个游戏会话中,它根本不起作用;几乎就像脚本被删除或完全忽略的某种随机机会一样。如果我删除 debounce,脚本有 100% 的机会再次运行。这里可能出了什么问题?

local radius = script.Parent
local light = radius.Parent.Light
local sound = radius.Parent.lighton

local debounce = false

radius.Touched:connect(function(hit)
    if debounce == false then debounce = true
        if game.Players:GetPlayerFromCharacter(hit.Parent) then
            light.PointLight.Brightness = 10
            light.Material = "Neon"
            sound:Play()
            wait(5.5)
            light.PointLight.Brightness = 0
            light.Material = "Plastic"
            sound:Play()
            wait(0.5)
            debounce = false
        end
    end
end)

您的问题是范围界定问题。 debounce 将始终设置为 true,但有时会设置回 false。如果不更改,该函数显然再也不会 运行 了。你会想要避免像 if debounce == false then debounce = true 这样的行,因为它们让你更难注意到去抖在同一范围内没有改变。

固定码:

local radius = script.Parent
local light = radius.Parent.Light
local sound = radius.Parent.lighton

local debounce = false

radius.Touched:connect(function(hit)
    if debounce == false then
        debounce = true
        if game.Players:GetPlayerFromCharacter(hit.Parent) then
            light.PointLight.Brightness = 10
            light.Material = "Neon"
            sound:Play()
            wait(5.5)
            light.PointLight.Brightness = 0
            light.Material = "Plastic"
            sound:Play()
            wait(0.5)
        end
        debounce = false
    end
end)

请注意,两个更改 debounce 值的语句对齐。