如何在 Roblox 中触发 MouseButton1Click 事件?
How to trigger a MouseButton1Click event in Roblox?
我有一个按钮,我想触发玩家通过另一个脚本点击它时发生的事件。我试过 button.MouseButton1Click()
但没用。我怎样才能实现它?
您需要将点击事件连接到函数:
button.MouseButton1Click:Connect(function()
--whatever code you want to happen after the button is clicked goes here
end)
如果您想重用代码,我建议您查看 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()
但没用。我怎样才能实现它?
您需要将点击事件连接到函数:
button.MouseButton1Click:Connect(function()
--whatever code you want to happen after the button is clicked goes here
end)
如果您想重用代码,我建议您查看 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()
这样您就不必伪造鼠标点击,您的代码只是存在于一个可共享的位置。