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

Why is the user data nil?

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

✓ Accepted answer

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

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