Confused on how to get the player from a character

So I’m trying to get the player from the character that touched a part. Using that information I would like to change the brick color of another part. As a disclaimer, I’m not entirely sure how the GetPlayerFromCharacter() function works as the API on that particular entry confused me. Nevertheless, this is how I tried to implement it.

local teams = game:GetService("Teams")

script.Parent.Touched:Connect(function(plr)
	local playersService = game:GetService("Players")
	local player = playersService:GetPlayerFromCharacter(plr.Parent)
		
	if player.Team == "Navy blue" then
		script.Parent.Parent.pole1.BrickColor = BrickColor.new("Navy blue")
	end
end)

image

This tells me that there is something wrong with how I’m trying to get the player, but I’m not sure how I would go about getting the player from the player’s character.

I also just realized I forgot to reference the player’s team color, but that’s not the issue I’m having with getting the player from the character.

What happens if you move playersService outside of the function?

The same thing as before it seems.

Check if the player actually exists. If the parent of the touched part isn’t the player’s character then GetPlayerFromCharacter would return nil. For example, if you touch the part with your hat, then plr would be the hat Handle and plr.Parent would be the hat accessory

1 Like

Change this line:

if player and player.TeamColor == BrickColor.new("Navy blue") then

Touched is for checking collisions between two parts where the other part is passed as the argument, so that’s probably confusion point one here - you’re using the shorthand for player as the variable referencing a touching part.

Your use of GetPlayerFromCharacter is accurate (your Players service variable should be beside the Teams one though, for consistency’s sake). That being said, as your script is trying to index something from nothing, you also need a check to see if GetPlayerFromCharacter actually returned anything.

Last thing is that Team is a reference to the Team object of the player’s current team. If you want that code to work, you should instead be checking the name of the TeamColor. Ideal because you’d be comparing strings here.

local Teams = game:GetService("Teams")
local Players = game:GetService("Players")

script.Parent.Touched:Connect(function (part)
    local player = Players:GetPlayerFromCharacter(part.Parent)

    if player and player.TeamColor.Name == "Navy blue" then
        -- Recolour pole1
    end
end)
2 Likes

That was the solution, I’ve reviewed all the input received here and I thank everyone for helping me. I feel like I’ve got a grasp on that function as well as a few other things now.