Search code examples
luascriptingroblox

Attempt to index nil with 'InLobby'


i was trying to make a button that sets if the player is immortal or no, but it gave me error "Attempt to index nil with 'InLobby'"

Server script

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)

Client script (In the button 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)

Solution

  • The error is telling you that game:GetService('Players'):FindFirstChild(plr) is returning nil, meaning that it is not finding the player you are looking for. That is because FindFirstChild expects you to pass it the string name of the child and you have passed it a Player object.

    But why are you searching for the player at all? You already have it in the form of the plr variable.

    Now, assuming that you have a BoolValue as a child of the player, try this :

    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)