为什么这段代码不能将变量改为真或假

问题

我正在制作 Roblox 中的一款游戏。我正在工作中,尝试使用补间动画来使 GUI 的界面变化,但是我的代码不能修改我正在使用的名为state的变量。State变量应该指示它是打开还是关闭状态(State=true表示打开,否则,State=false)。

我尝试将变量设为本地化变量,但仍然输出相同。我通过打印state变量来检查输出值,但这个输出总是等于默认值。

代码


-- 本地变量
local Frame = script.Parent.Parent.Parent.Parent.Parent.MinerGuiManager.MinerFrame
State = false
local Button = script.Parent.Button

-- 打开/关闭语句

if State == true then
    Button.Text = '关闭!'
    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 = '打开!'
    script.Parent.Button.MouseButton1Click:connect(function()
    Frame:TweenPosition(UDim2.new(0.305,0,0.25,0,'Bounce',1.5))
    State = true
end)
end

我期望代码输出是将变量state设置为打开时为 True,关闭时为 False。

点赞
用户1442917
用户1442917

你在 Frame:TweenPosition(UDim2.new(0.3,0,1.2,0)) 这一行之后缺失了 State = false。在它的值被修改成 true 之后,你从未将它改回 false

2019-06-11 04:35:09
用户2860267
用户2860267

你需要小心如何连接你的 Mouse1Click 事件监听器。

当你从上到下阅读你的脚本时,你会发现 State 起始为 false,你只连接了第二个监听器。这意味着当你点击按钮时,它只会把框架缓动到打开状态。最好写一个单击处理程序,在每次单击时处理此逻辑。

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)
2019-06-12 05:53:34