【发布时间】:2021-04-13 03:38:26
【问题描述】:
我有一个按钮,我想触发当玩家通过另一个脚本点击它时发生的事件。我试过button.MouseButton1Click(),但没用。我怎样才能实现它?
【问题讨论】:
-
你真正想要达到什么目的?我闻到了xy-problem。为什么不简单地调用事件监听器?
我有一个按钮,我想触发当玩家通过另一个脚本点击它时发生的事件。我试过button.MouseButton1Click(),但没用。我怎样才能实现它?
【问题讨论】:
如果您想重用代码,我建议您查看ModuleScripts。您可以在 ModuleScript 中编写共享代码功能,然后在需要的地方使用它。
所以在 ReplicatedStorage 中的 ModuleScript 中,您可能会有类似的内容:
local Foo = {}
function Foo.DoSomething()
print("Doing the thing!")
-- add your other behaviors here!
end
return Foo
然后,在您的代码中使用您的按钮:
local Foo = require(game.ReplicatedStorage.Foo) -- put the path to your ModuleScript
local button = script.Parent
button.MouseButton1Click:Connect(function()
Foo.DoSomething()
end)
你也可以在另一个脚本中做同样的事情!
local Foo = require(game.ReplicatedStorage.Foo)
Foo.DoSomething()
这样您就不必伪造鼠标点击,您的代码只是存在于一个可共享的位置。
【讨论】:
您需要将点击事件连接到一个函数:
button.MouseButton1Click:Connect(function()
--whatever code you want to happen after the button is clicked goes here
end)
【讨论】: