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

How can i find a player from a tool?

Asked by 4 years ago
Edited 4 years ago

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

01local Tool = script.Parent
02 
03function Hit(PartOther)
04    local players = game.Players
05    local OtherCharacter = PartOther.Parent
06 
07    local CheckWorkspace = game.Players:FindFirstChild(OtherCharacter)
08 
09    print(CheckWorkspace)
10end
11 
12script.Parent:WaitForChild("Handle").Touched:Connect(Hit)

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

1 answer

Log in to vote
1
Answered by 4 years ago

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.

1local Players = game:GetService("Players")
2local Tool = script.Parent
3 
4Tool:WaitForChild("Handle").Touched:Connect(function(part)
5    local Player = Players:GetPlayerFromCharacter(part.Parent)
6    if Player then --make sure it exists
7        print(Player.Name)
8    end
9end)

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.

Ad

Answer this question