Roblox Studio报错:Attempt to index nil with 'Connect'求助
问题:Roblox脚本报错
attempt to index nil with 'Connect' 报错详情
报错信息:
Workspace.Script:30: attempt to index nil with 'Connect'
出错代码行:
players.PlayerAdded:Connect(function(player) -- line 30 if player.UserId == alertaCorUserId then alertaCorEvent:FireClient(player, true) else alertaCorEvent:FireClient(player, false) end end)
完整脚本
local players = game:GetService("Players"):GetPlayers() if #players > 0 then local alertaCorUserId = players[math.random(1, #players)].UserId local ReplicatedStorage = game:GetService("ReplicatedStorage") local alertaCorEvent = ReplicatedStorage:FindFirstChild("AlertaCorEvent") if not alertaCorEvent then alertaCorEvent = Instance.new("RemoteEvent") alertaCorEvent.Name = "AlertaCorEvent" alertaCorEvent.Parent = ReplicatedStorage end if alertaCorEvent then players.PlayerAdded:Connect(function(player) if player.UserId == alertaCorUserId then alertaCorEvent:FireClient(player, true) else alertaCorEvent:FireClient(player, false) end end) alertaCorEvent.OnServerEvent:Connect(function(player, isAlertaCor) if isAlertaCor then print(player.Name .. " is Alerta Cor!") else print(player.Name .. " isn't Alerta Cor!") end end) else warn("Erro: alertaCorEvent is nil.") end else warn("No players to be selected") end
问题分析与修复
核心错误原因
变量players是通过game:GetService("Players"):GetPlayers()获取的当前在线玩家数组,它只是一个普通Lua表,没有PlayerAdded事件。PlayerAdded是Players服务对象专属的事件,因此调用players.PlayerAdded会得到nil,后续调用:Connect()自然触发报错。
修复步骤
- 分离
Players服务引用与玩家列表:单独获取Players服务对象,用它绑定PlayerAdded事件,玩家列表仅用于初始玩家的状态发送。 - 处理初始在线玩家:脚本启动时已在线的玩家不会触发
PlayerAdded,需要手动遍历列表发送状态。
修复后的完整脚本
-- 获取Players服务对象 local PlayersService = game:GetService("Players") -- 获取当前在线玩家列表 local players = PlayersService:GetPlayers() if #players > 0 then local alertaCorUserId = players[math.random(1, #players)].UserId local ReplicatedStorage = game:GetService("ReplicatedStorage") local alertaCorEvent = ReplicatedStorage:FindFirstChild("AlertaCorEvent") if not alertaCorEvent then alertaCorEvent = Instance.new("RemoteEvent") alertaCorEvent.Name = "AlertaCorEvent" alertaCorEvent.Parent = ReplicatedStorage end if alertaCorEvent then -- 复用状态发送逻辑 local function sendAlertaCorStatus(player) local isAlertaCor = player.UserId == alertaCorUserId alertaCorEvent:FireClient(player, isAlertaCor) end -- 绑定PlayerAdded事件(使用Players服务对象) PlayersService.PlayerAdded:Connect(function(player) sendAlertaCorStatus(player) end) -- 给初始在线玩家发送状态 for _, player in ipairs(players) do sendAlertaCorStatus(player) end alertaCorEvent.OnServerEvent:Connect(function(player, isAlertaCor) if isAlertaCor then print(player.Name .. " 是Alerta Cor!") else print(player.Name .. " 不是Alerta Cor!") end end) else warn("错误:alertaCorEvent 为空。") end else warn("没有玩家可以被选中") end
额外说明
- 初始在线玩家不会触发
PlayerAdded事件,必须手动遍历发送状态,否则这些玩家无法收到事件通知。 - 提取复用函数
sendAlertaCorStatus可以减少代码冗余,方便后续逻辑修改。
内容的提问来源于stack exchange,提问作者Emi Nave
相关产品推荐
相关产品推荐

