Roblox开发求助:制作无敌按钮时出现Attempt to index nil with 'InLobby'报错
问题解决:"Attempt to index nil with 'InLobby'"报错修复
报错根源
你服务端脚本里存在两个关键问题:
- 错误使用
FindFirstChild:OnServerEvent回调传入的plr本身就是触发事件的Player对象,不需要再通过game:GetService('Players'):FindFirstChild(plr)查找——FindFirstChild需要传入字符串类型的玩家名称,你传入Player实例会直接返回nil,自然无法索引InLobby属性。 - Color3取值错误:客户端脚本里
Color3.new(0, 255, 0)的RGB值超出范围,Color3的取值区间是0到1,255会导致颜色异常。
修复后的完整脚本
服务端脚本
local event = game:GetService('ReplicatedStorage').DieButton event.OnServerEvent:Connect(function(plr: Player) print(plr.Name .. " has become immortal!") -- 直接操作传入的Player对象,简化布尔值切换逻辑 plr.InLobby.Value = not plr.InLobby.Value end)
客户端脚本(位于按钮GUI中)
local event = game:GetService('ReplicatedStorage').DieButton script.Parent.MouseButton1Click:Connect(function() local btn = script.Parent if btn.Text == "die" then btn.Text = "dien't" btn.BackgroundColor3 = Color3.new(1, 0, 0) else btn.Text = "die" btn.BackgroundColor3 = Color3.new(0, 1, 0) -- 修正Color3取值范围 end event:FireServer() end)
额外必做检查
确保玩家对象上存在InLobby BoolValue实例,否则仍会报错。可以在玩家加入时自动创建该实例:
-- 放在服务端脚本中(例如ServerScriptService内) game.Players.PlayerAdded:Connect(function(plr) local inLobby = Instance.new("BoolValue") inLobby.Name = "InLobby" inLobby.Value = true -- 根据需求设置初始值 inLobby.Parent = plr end)
内容的提问来源于stack exchange,提问作者EndeX
相关产品推荐
相关产品推荐

