Roblox studio 尝试使用 getMouse() 索引 nil 时出错

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

所以,我的代码是这样的:

while game.Players.LocalPlayer == nil do
    player = game.Players.LocalPlayer
    wait(0.1)
end




local mouse = player:GetMouse()


mouse.Button1Up:Connect(addpoints())

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

错误出现在本地鼠标=玩家:GetMouse()这一行上,while循环是为了找到本地玩家而不是得到nil,因为脚本在你加入游戏时运行,所以如果它立即运行,它会得到nil。但由于某种原因,玩家仍然得到 nil,然后我收到错误尝试使用 getMouse() 索引 nil

lua roblox
2个回答
0
投票

如果脚本位于 StarterPlayerScripts 中的某个位置,我认为您不必等待玩家,因为如果“玩家”不是东西,则脚本将无法工作。 你的问题最可能的原因是因为 game.Players.LocalPlayer 已经是一个东西了,所以它不会返回

nil
,所以脚本甚至懒得进入 while 循环,所以你永远不会设置
player
变量。

但是如果你仍然想确定玩家是一个东西,这应该可行:

local player = game.Players.LocalPlayer
while player == nil do
    print("Player is nil")
    -- you will see this wont print anything since the game.Players.LocalPlayer is not nil
    player = game.Players.LocalPlayer
    wait(0.1)
end

local mouse = player:GetMouse()
mouse.Button1Up:Connect(addpoints)
function addpoints()
    print("add points")
end

0
投票

我知道我迟到了半年,但我是新人,所以我需要 rp。

首先,就像@xlAsdas 所说,你甚至不需要 while 循环。

第二件事,你需要先定义函数。

这是我测试过的工作代码:

本地玩家 = game.Players.LocalPlayer 本地鼠标 = 玩家:GetMouse()

函数addpoints() print("加点") 结束

mouse.Button1Up:连接(添加点)

另一种方法是在连接内部定义函数,如下所示:

本地玩家 = game.Players.LocalPlayer 本地鼠标 = 玩家:GetMouse()

鼠标.Button1Up:连接(function() print("加点") 结束)

而且我不知道如何正确添加代码,因为我是新人。

© www.soinside.com 2019 - 2024. All rights reserved.