首页 > 解决方案 > 我正在尝试编写一个脚本来告诉我鼠标何时进入和离开 Roblox Studio 中的 ClickDetector

问题描述

这是代码。

local detector = script.Parent.ClickDetector -- setting a click detector variable to save time
function mousein() -- mousein function
    print("Mouse has entered!") -- print "Mouse has entered!" in the output
end -- end of the function
function mouseout()-- mouseout function
    print("Mouse has left!") -- print "Mouse has left!" in the output
end -- end of the function
detector.MouseHoverEnter:Connect(mousein) -- run mousein when my mouse hovers over the clickdetector
detector.MouseHoverLeave:Connect(mouseout)-- run mouseout when my cursor leaves the clickdetector

我标记了代码以使其更易于阅读。 请将工作代码放在答案中!
这是我在 StackOverflow 上的第一个问题。我是编码新手。

标签: luamouseeventmouselistenerrobloxonmouseover

解决方案


您需要创建ClickDetector实例。

local detector = Instance.new("ClickDetector")
detector.Parent = thing --whatever object you want to detect mouse stuff on
detector.MaxActivationDistance = 10

function mousein()
    print("Mouse has entered!")
end
function mouseout()
    print("Mouse has left!")
end

detector.MouseHoverEnter:Connect(mousein)
detector.MouseHoverLeave:Connect(mouseout)

或者,如 API 文档中所述,为了script.Parent.ClickDetector按预期工作,它必须放在ScriptLocalScriptClickDetector

APIREFERENCE > INPUT > CLICKDETECTOR > MouseHoverEnter


推荐阅读