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

How to get Player from a touched part?

Asked by 7 years ago
Edited 7 years ago
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)

0
You have to check if what touched the part was a player character part. (if player then) OldPalHappy 1477 — 7y
0
Can you implement that into the script and post it as an answer so I can accept and fully understand what you mean? SchonATL 15 — 7y

1 answer

Log in to vote
1
Answered by
Mayk728 855 Moderation Voter
7 years ago
Edited 7 years ago

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)
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? SchonATL 15 — 7y
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. Mayk728 855 — 7y
Ad

Answer this question