我试图制作一个按钮,如果玩家是不朽的或没有,但它给了我错误"尝试索引nil与'InLobby'">
服务器脚本
local event = game:GetService('ReplicatedStorage').DieButton
event.OnServerEvent:Connect(function(plr: Player)
print(plr.Name.."has become immortal!")
if game:GetService('Players'):FindFirstChild(plr).InLobby.Value == true then
game:GetService('Players'):FindFirstChild(plr).InLobby.Value = false
else
game:GetService('Players'):FindFirstChild(plr).InLobby.Value = true
end
end)
客户端脚本(在按钮gui)
local event = game:GetService('ReplicatedStorage').DieButton
script.Parent.MouseButton1Click:Connect(function()
if script.Parent.Text == "die" then
script.Parent.Text = "dien't"
script.Parent.BackgroundColor3 = Color3.new(1, 0, 0)
else
script.Parent.Text = "die"
script.Parent.BackgroundColor3 = Color3.new(0, 255, 0)
end
event:FireServer()
end)
错误告诉你game:GetService('Players'):FindFirstChild(plr)
返回nil
,这意味着它没有找到你正在寻找的玩家。这是因为FindFirstChild期望你给它传递子对象的字符串名,而你已经给它传递了一个Player对象。
但是你为什么要搜索玩家呢?您已经以plr
变量的形式获得了它。
现在,假设你有一个BoolValue作为播放器的子元素,试试这个:
local event = game:GetService('ReplicatedStorage').DieButton
event.OnServerEvent:Connect(function(plr: Player)
print(plr.Name.."has become immortal!")
local InLobby = plr.InLobby
InLobby.Value = not InLobby.Value
end)