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

How to get Player from a touched part?

script.Parent.Touched:connect(function(hit)
	local player = game.Players:GetPlayerFromCharacter(hit.Parent)
	if player.Team == "Red" then
		script.Parent.Parent.RedOccupied.Value = script.Parent.Parent.RedOccupied.Value + 1
	elseif player.Team == "Blue" then
		script.Parent.Parent.BlueOccupied.Value = script.Parent.Parent.BlueOccupied.Value + 1
	end
end)

Error:

00:29:15.515 - Workspace.MountainFlag.FlagTrigger.Script:3: attempt to index local 'player' (a nil value)

2 comments

0

You have to check if what touched the part was a player character part. (if player then)

0

Can you implement that into the script and post it as an answer so I can accept and fully understand what you mean?

1 answer

What you need to do is access your character from workspace then you can use :GetPlayerFromCharacter()

EDIT: You need to make the script only detect a player. Make sure it checks if the touched part has a Humanoid.

Here is the [New] fixed script:

script.Parent.Touched:connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		local plr = workspace[hit.Parent.Name] --Access character from workspace.
		local player = game.Players:GetPlayerFromCharacter(plr) --Access (plr)
		if player.Team == "Red" then
			script.Parent.Parent.RedOccupied.Value = script.Parent.Parent.RedOccupied.Value + 1
		elseif player.Team == "Blue" then
			script.Parent.Parent.BlueOccupied.Value = script.Parent.Parent.BlueOccupied.Value + 1
		end
	end
end)

2 comments

0

That gives me errors such as "13:03:04.385 - Headphones is not a valid member of Workspace". Must be a new ROBLOX update?

0

Ah i know, when you use the script for touches, it detects everything, even parts. I'll fix it to make it only detect a player.

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