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

GetPlayerFromCharacter doesn't work?

Asked by
Oficcer_F 207 Moderation Voter
5 years ago

This is my script:

Why doesnt it give points?

script.Parent.Touched:Connect(function(hit)

    char = hit.Parent
    player = game.Players:GetPlayerFromCharacter(char)
    if hit.Parent:FindFirstChild("BlueFlag")then
        char.BlueFlag.Parent = game.Workspace
        player.leaderstats.Points.Value = player.leaderstats.Points.Value + 100
        game.Workspace.BlueFlag.RemoveWeld:Invoke()
        game.Workspace.BlueFlag.Position = Vector3.new(69.5, 0.5, 40)
        game.Workspace.BlueFlag.Anchored = true
        end
end)

ERROR: attempt to index global 'player' (a nil value)

Why?

1 answer

Log in to vote
4
Answered by 5 years ago
Edited 5 years ago

The reason this is happening is because GetPlayerFromCharacter returned nil, because char was actually the Workspace, or some other Model that touched the part. In order to fix this, you will have an if statement that checks if the player exists.

local blueFlag = workspace.BlueFlag -- don't repeat yourself! Have a variable for blueflag

script.Parent.Touched:Connect(function(hit)
    local model = hit.Parent -- use local variables! usage of global variables is bad practice 
    local player = game.Players:GetPlayerFromCharacter(char)

    if model:FindFirstChild("BlueFlag") and player then -- if there is a player 
        char.BlueFlag.Parent = game.Workspace
        player.leaderstats.Points.Value = player.leaderstats.Points.Value + 100
        blueFlag.RemoveWeld:Invoke()
        blueFlag.Position = Vector3.new(69.5, 0.5, 40)
        blueFlag.Anchored = true
    end
end)


1
Road to 6K!! Almost congrats incapaz! mixgingengerina10 223 — 5y
Ad

Answer this question