为什么此代码不将变量更改为 True 或 False

Why isn't this code changing the variable to True Or False

问题

所以目前,我正在 Roblox 中制作游戏。我正在对我的一个 GUI 进行补间,但是代码并没有改变我正在使用的名为 state 的 var。 state var 应该告诉它是打开还是关闭(如果打开,State = true,否则,State = false)。

我试图将变量设为局部变量。但仍然是相同的输出。我通过打印 state 变量来检查输出。这将始终与默认值相同。

代码


-- Local Variables
local Frame = script.Parent.Parent.Parent.Parent.Parent.MinerGuiManager.MinerFrame
State = false
local Button = script.Parent.Button


-- Open/Close Statements

if State == true then
    Button.Text = 'Close!'
    script.Parent.Button.MouseButton1Click:connect(function()
    Frame:TweenPosition(UDim2.new(0.3,0,1.2,0))
    State = false
end)
end

if State == false then
    Button.Text = 'Open!'
    script.Parent.Button.MouseButton1Click:connect(function()
    Frame:TweenPosition(UDim2.new(0.305,0,0.25,0,'Bounce',1.5))
    State = true
end)
end

我希望代码的输出设置 var state 在打开时为 True,在关闭时为 False。

您在 Frame:TweenPosition(UDim2.new(0.3,0,1.2,0)) 行后缺少 State = false。在将其更改为 true.

后,您永远不会将其值切换回 false

您需要小心连接 Mouse1Click 事件侦听器的方式。

当您从上到下阅读脚本时,您会发现由于 State 开始时为 false,您连接的唯一侦听器是第二个侦听器。这意味着当您单击按钮时,它只会将 Frame 补间到打开状态。最好编写一个点击处理程序来处理每次点击的逻辑。

local Button = script.Parent.Button
local Frame = script.Parent.Parent.Parent.Parent.Parent.MinerGuiManager.MinerFrame
State = false

Button.MouseButton1Click:connect(function()
    if State == true then
        Button.Text = 'Close!'
        Frame:TweenPosition(UDim2.new(0.3,0,1.2,0))
    else
        Button.Text = 'Open!'
        Frame:TweenPosition(UDim2.new(0.305,0,0.25,0,'Bounce',1.5))
    end)

   State = not State
end)