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

What is the GetPlayerFromCharacter Function?

Can you guys tell me in a full explanation what this means? I looked on the Roblox Wiki and it still doesn't make sense to me. Thanks.

1 answer

✓ Accepted answer

The GetPlayerFromCharacter function "returns the Player associated with the given character, or nil if the character is not controlled by a player"

If you have a player's character model (the physical model), you can find the corresponding Player instance for that character (the object in the Players service which has GUIs and the StarterGear and PlayerPack).

The essential is that it "undoes" player.Character, that is,

game.Players:GetPlayerFromCharacter( player.Character ) is player.


Because it returns nil (as opposed to erroring) you can also use this to determine if a given model is actually a ROBLOX player rather than something else in, for example, a Touched event:

-- Example touched event to give a player a weapon
function onTouch(hit)
	if hit.Parent then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent);
		if player then
			game.ReplicatedStorage.Weapon:Clone().Parent = player.PlayerPack;
		end
	end
end
somepart.Touched:connect(onTouch);

7 comments

1

What do you mean by onTouch(hit)? What is the hit for?

2

That was just an example... For Touched event functions, the parameter is called hit by most people. I'm not really sure why. It's the parameter referring to what object touched somepart in this case

1

Thanks. I just got one more question. When you say "if hit.Parent then", what is the parent for? I know what it is but i'm just confused on how you used it. Sorry for asking so many questions. I'm a somewhat-new person to scripting and just started learning a couple days ago.

2
  1. Parent is the container of an instance. So, for a brick, its parent will usually be the model that contains it. 2) if (something) then can be used to make sure (something) exists (if it's nil, the condition fails). 3) Putting these together, this makes sure that hit.Parent exists before continuing (hit.Parent can be nil from bullets that get deleted upon contact with something)
2

Also please remember to use the check mark and upvote anything you can that you find helpful -- it encourages people to provide answers as well identify that a problem is already solved

1

Everything was helpful. Thank you so much! I finally understand! By the way, I would upvote all your comments, but I don't have any reputation so I can't right now. Thanks so much though!

2

Okay :) I really don't know the points stuff breaks down, I just like to be helpful and see helpful things everywhere here actually get noted

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