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 use of :GetPlayerFromCharacter()?

So I am trying to make a simulator game and I don't understand how :GetPlayerFromCharacter works. I read https://developer.roblox.com/en-us/api-reference/function/Players/GetPlayerFromCharacter but I still don't understand. Can anyone explain what it does with low scripting vocabulary. Thank You

local function Sell(player)
	local blocks = player:WaitForChild("leaderstats"):WaitForChild("blocks")
	local coins =  player:WaitForChild("leaderstats"):WaitForChild("coins")
	local add = blocks.Value * multiplier
	coins.Value = coins.Value + add
	blocks.Value = 0
end

local function touched(Part)
	if game.Players:GetPlayerFromCharacter(Part.Parent) then
		Sell(game.Players:GetPlayerFromCharacter(Part.Parent))
	end
end

script.Parent.Touched:Connect(touched)

2 answers

✓ Accepted answer

Players:GetPlayerFromCharacter() allows you to touch a part somewhat similar to hit.Parent:FindFirstChild("Humanoid"). The problem with hit.Parent:FindFirstChild("Humanoid") is that it detects NPCs as well. Not only it can be used to rule out NPCs, it can also be used to detect Players. For example, if you're trying to make a Pop-Up Gui by touching a part, you need to detect a player and not an NPC otherwise it would break your script. Players:GetPlayerFromCharacter() just simply allows you to find players, and not anything else.

It returns the Player object controlling a given character. It's like the opposite of getting Player.Character.

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