local function onTouched(player) local level = game.Players.player.leaderstats.Level level.Value = level.Value + 1 end script.Parent.Touched:connect(onTouched)
Line 1 is giving me the error player is not a valid member of Players.
I've tried look this up and didn't find anything, thanks to anyone who helps out! :)
That's because you are trying to find an object named 'player' inside the Players service, which doesn't exist. Additionally, the returned object isn't a player, it's the part that touched. Since the part that touched it can be a limb of a player, we can use the method GetPlayerFromCharacter
checking if the parent of the part (the potential character model) has a player.
(On a smaller note, connect is deprecated. Please use Connect.)
function onTouched(hit) local player = game.Players:GetPlayerFromCharacter(hit.Parent) if player then -- Found the player! Do your logic here. end end script.Parent.Touched:Connect(onTouched)
Also try to fix that formatting up a little bit. Your code needs to be neat and organized, otherwise you won't understand it.
This is because the BasePart.Touched
event returns the BasePart
that touched the part. It could be a limb, torso, head, or a part that doesn’t belong to a player. Because of this, you must use the GetPlayerFromCharacter
method of the Players
service. You should also use Connect
since ROBLOX may remove connect
soon.
local plrs = game:GetService"Players" local function onTouch(part) -- part is our parameter if part.Parent:FindFirstChild"Humanoid" then -- if we find a humanoid local plr = plrs:GetPlayerFromCharacter(part.Parent) -- self explanatory if plr then -- make sure it’s a player, not a part that fell from the sky or something local level = plr.leaderstats.Level level.Value = level.Value + 1 end end end script.Parent.Touched:Connect(onTouch)