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

How do i get a player?

Asked by 10 years ago

I have this brick that destroys head on touch through a ontouch function, but i dont know how to get a player? Even if i type my own name, it only works once, then it fails,

1 answer

Log in to vote
0
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

You use the GetPlayerFromCharacter(chr) method of Players.

script.Parent.Touched:connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    print(player)
end)

However, this code is bad. If an AI or another brick touches this brick, we will get an error because there is no player. We can fix this with a simple if statement.

script.Parent.Touched:connect(function(hit)
    if game.Players:GetPlayerFromCharacter(hit.Parent) then
        local player = game.Players:GetPlayerFromCharacter(hit.Parent)
        print(player)
    end
end)
Ad

Answer this question