Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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?

4 comments

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

0

Ok, I'll try some things out. Also, this was ran into a server script.

0

Also don't use :len() to get the string length. Instead, use the unary length operator #. #str

0

I tried many things, but nothing worked

1 answer

✓ Accepted answer

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.