我的Roblox脚本正常运行,但一旦添加了debounce,它仍然表现完美,但有时只能运行一部分?

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

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

-- 设置变量 debounce 为 false
local debounce = false

-- 当 radius 被触碰时,执行以下代码
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 以便下次可以再次触发
            debounce = false
        end
    end
end)
点赞
用户2104791
用户2104791

你的问题是作用域之一。Debounce将始终设置为true,但仅有时会被设置为false。如果未对其进行更改,函数显然永远不会再次运行。你应该避免像 if debounce == false then debounce = true 这样的代码行,因为它们会使你更难注意到在相同作用域中Debounce没有更改。

修正后的代码:

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

local debounce = false

radius.Touched:connect(function(hit)
    if not debounce 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值的两个语句是对齐的。

2015-10-20 00:12:36