Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Trying to get a player from a function but I get an error?

Asked by
KDarren12 705 Donator Moderation Voter
4 years ago
Edited 4 years ago

Here is my code:

function GetPlayer(targetedPlayerName)
      for _,player in pairs(game:GetService("Players"):GetPlayers()) do
            if targetedPlayerName:lower() == player.Name:sub(1,targetedPlayerName:len()):lower() then
                return player
            end
        end
        return nil
end

script.Parent.MouseButton1Click:Connect(function()
    local txt = script.Parent.Parent.NameInput.Text
    local plr = GetPlayer(txt)
        plr.Character:FindFirstChild("Humanoid").Health = 0
    end)

Here is a Lightshot Screenshot that shows my Explorer GUI: http://prntscr.com/opbe2m

When I got the error, " 20:51:16.334 - Players.KDarren12.PlayerGui.ScreenGui.Frame.KickButton.Keeeek script:13: attempt to index local 'plr' (a nil value)", I wanted to make sure I targeted the text input correctly, and I did. Any help please?

0
Because there was no player whose name contained the text inputted. You need to check if the player exists first. Also killing players locally won't replicate to the server. You need remote events but this could be abused by exploiters. You're better off using chat commands or something like admin cmds User#24403 69 — 4y
0
Ok, I'll try some things out. Also, this was ran into a server script. KDarren12 705 — 4y
0
Also don't use :len() to get the string length. Instead, use the unary length operator #. #str User#24403 69 — 4y
0
I tried many things, but nothing worked KDarren12 705 — 4y

1 answer

Log in to vote
1
Answered by 4 years ago

I think the problem is that you're running all this in a ServerScript, as opposed to a LocalScript. After running a few tests myself, it seems the ServerScript wouldn't recognise the updated text in the TextBox, hence to it the text was always "". I suggest you try running the same code in a LocalScript. Note, however, that when you transfer to a LocalScript you won't be able to run this line of code: plr.Character:FindFirstChild("Humanoid").Health = 0 because it won't replicate to the server and other clients (ie, the player won't be killed for anyone else). You'll need to use a RemoteEvent to connect with the server to kill the player.

Ad

Answer this question