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

How can i find a player from a tool?

so tool that when another player is hit by, it finds them in the games players and kicks them

local Tool = script.Parent

function Hit(PartOther)
	local players = game.Players
	local OtherCharacter = PartOther.Parent

	local CheckWorkspace = game.Players:FindFirstChild(OtherCharacter)

	print(CheckWorkspace)
end

script.Parent:WaitForChild("Handle").Touched:Connect(Hit)

My output always prints nil and im not sure what im doing wrong

1 answer

✓ Accepted answer

The issue is that you're searching the Players service for the actual otherCharacter object. If you simply used otherCharacter.Name in your :FindFirstChild(), it would work just fine. However, I would suggest using :GetPlayerFromCharacter(), instead, as shown below.

local Players = game:GetService("Players")
local Tool = script.Parent

Tool:WaitForChild("Handle").Touched:Connect(function(part)
	local Player = Players:GetPlayerFromCharacter(part.Parent)
	if Player then --make sure it exists
		print(Player.Name)
	end
end)

Also, notice how I changed your function a bit. Instead of having a named function, like you did, I turned it into a silent function. Truthfully, the only reason I do this is when I know I'm not going to call the function in the future. In your case, the function is bound to an event, so you probably won't be calling it again. This keeps one less variable out of the stack, keeping your namespace tidy and improving efficiency.

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