Roblox Studio 如何切换打印信息的开关

当我按下 P 键时,我希望脚本能够打印"Printed",但只有当工具已装备时才能打印。如果工具未装备,我希望将其切换关闭。

然而,当我测试代码时,即使在卸下工具后,打印信息仍然没有被切换关闭,仍然打印 "Printed"。我这里做错了什么?

tool = script.Parent
handle = tool.Handle
a = false

tool.Equipped:Connect(function()
    if a == false then
        a = true
         game:GetService("UserInputService").InputBegan:Connect(function(P)
            if P.KeyCode ==Enum.KeyCode.P then
                print ("Pressed")
            end
        end)
    end

    tool.Unequipped:Connect(function()
        if a == true then
            a = false
        end
    end)
end)
点赞
用户5373986
用户5373986

在 Lua 中,一旦你进行了:Connect语句,这个语句将会在每次它所附加到的触发器被触发时运行。

这意味着一旦你的代码运行一次并且执行了那个game:GetService("UserInputService").InputBegan:Connect(调用,它将会运行无论等于 true 还是 false。你想要的是检查在:Connect调用内部。

这可能是你在这里要寻找的:

Tool = script.Parent
Handle = tool.Handle
Run = false

Tool.Equipped:Connect(function()
    Run = true
end)

Tool.Unequipped:Connect(function()
    Run = false
end)

Game:GetService("UserInputService").InputBegan:Connect(function(P)
    if P.KeyCode == Enum.KeyCode.P and Run == true then
        print ("Pressed")
    end
end)

Run = true检查意味着只有在按下 P 并且装备了工具时才会运行打印。如果你想要它运行的方式相反,你可以交换truefalse的赋值。

2018-08-20 16:44:49