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

Why is the user data nil?

Asked by 5 years ago

so I have this script that seems to work in studio but turns bad in game. Any ideas?

wait(10)

function a(hit)
    local b = hit.Parent.Name
    local user = game.Players:findFirstChild(b)
    user.TeamColor = script.Parent.BrickColor
    user.Backpack:ClearAllChildren()
    wait(1)
end
script.Parent.Touched:connect(a)

1 answer

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

Problems


Couple of things there ,

  • one, you unnecessarily waited 10 seconds for what ever reason.

  • two, you never truly checked if the player existed,

  • three, declaring a function then only using it in an event, which is unnecessarily elongating code.


Solution


script.Parent.Touched:Connect(function (hit)
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
    if plr then
        plr.TeamColor = script.Parent.BrickColor
        plr.Backpack:ClearAllChildren()
    end
end)

Note here that I used the GetPlayerFromCharacter function, which ensures that it is an actual player object, rather than something else with the same name positioned in the same area.

Also note that I checked if the player existed, then ran the code that only works if the player exists, so no errors ensued.

While the waits don't necessarily break the script, having them without a purpose is certainly not recommended in any way, shape, or form.

Hopefully this helped! Be sure to accept if it did

Ad

Answer this question