You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Roblox Studio报错:attempt to index nil with getMouse()求助

问题解决:LocalPlayer为nil导致的getMouse()错误

问题原因

  1. 你用while轮询等待LocalPlayer的方式存在不可靠性,可能因Roblox线程调度时机问题,导致player变量未正确捕获到玩家对象。
  2. 鼠标事件绑定写法错误:mouse.Button1Up:Connect(addpoints())会直接执行addpoints()函数,并将返回值(nil)传递给Connect,导致点击事件无法正常触发,正确写法应传递函数引用而非调用函数。

修正后的代码

-- 等待本地玩家加载完成,确保player非nil
local player = game.Players.LocalPlayer
if not player then
    player = game.Players.PlayerAdded:Wait()
end

local mouse = player:GetMouse()

-- 正确绑定鼠标左键抬起事件
mouse.Button1Up:Connect(addpoints)

function addpoints()
    print("add points")
end

更简洁的写法

-- 直接等待PlayerAdded事件返回本地玩家
local player = game.Players.PlayerAdded:Wait()
local mouse = player:GetMouse()

mouse.Button1Up:Connect(addpoints)

function addpoints()
    print("add points")
end

说明

  • game.Players.PlayerAdded:Wait()会暂停当前线程,直到本地玩家加载完成后返回玩家对象,从根源避免了player为nil的问题。
  • 事件绑定使用addpoints而非addpoints(),确保仅在触发事件时才执行函数逻辑。

内容的提问来源于stack exchange,提问作者Killercarrot102

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:55:21