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 3 years ago
Edited 3 years ago

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

Log in to vote
1
Answered by 3 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.

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.

Ad

Answer this question