如何在 Roblox 中触发 MouseButton1Click 事件?

问题描述 投票:0回答:3

我有一个按钮,我想触发当玩家通过另一个脚本单击它时发生的事件。我尝试了

button.MouseButton1Click()
但没有成功。我怎样才能实现它?

lua roblox
3个回答
0
投票

如果您想重用代码,我建议您查看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()

这样您就不必假装鼠标点击,您的代码只是存在于可共享的位置。


0
投票
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

mouse.Button1Down:Connect(function()
    print("Left mouse button was clicked")
end)

每当单击左键时,此代码都会打印出“单击鼠标左键”。 但我并没有真正得到你要求的东西。


-1
投票

您需要将 Click 事件连接到一个函数:

button.MouseButton1Click:Connect(function()
--whatever code you want to happen after the button is clicked goes here
end)
© www.soinside.com 2019 - 2024. All rights reserved.