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

What is the parent of UserId and why is my code erroring?

Asked by 6 years ago

So I have been scripting a door so that when you touch it some of your data will load into the game. Well for whatever reason the UserId is returning this error: "UserId is not a valid member of Model". Here is the code:

01script.Parent.Touched:Connect(function(hit)
02 
03    if hit.Parent:FindFirstChild("Humanoid") then
04 
05        local plr = hit.Parent
06        local specialKey = "User_"..plr.UserId
07 
08        -- more code here but that is irrelevant.
09 
10    end
11end)

What is even more confusing however, is the fact that in this script it works:

1game.Players.PlayerAdded:Connect(function(plr)
2 
3    local specialKey = "User_"..plr.UserId
4 
5end)

2 answers

Log in to vote
4
Answered by 6 years ago

You were trying to get the UserId from the player's Character rather than from the Player itself.

01script.Parent.Touched:Connect(function(hit)
02 
03    if hit.Parent:FindFirstChild("Humanoid") then
04 
05        local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
06        local specialKey = "User_"..plr.UserId
07 
08        -- more code here but that is irrelevant.
09 
10    end
11end)
1
Oh! Thank you so much. User#21908 42 — 6y
Ad
Log in to vote
1
Answered by 6 years ago

Hi Phlegethon,

The issue with your script is simple. One is addressing the Character, and one's addressing the player. The character is what appears in the server, it's your model in the game that's touchable and that has parts and others can see it. The player is in the Players, it's a Player Instance that has other information about the player. The Character is just a medium for the Player. Anyways, I won't get too into that but, your UserId is located in the player, not the character. So, that's why when you used the Players with the .PlayerAdded event, it worked because you were addressing the Player. The Character doesn't have the UserId. But, there's a simple fix for how to get the Player from the Character. Here, I'll show you how to do this using your script:

01script.Parent.Touched:Connect(function(hit)
02 
03    if hit.Parent:FindFirstChild("Humanoid") then
04 
05        local character = hit.Parent
06        local player = game.Players:GetPlayerFromCharacter(character); -- This gets the player from the character.
07    local specialKey = "User_"..player.UserId;
08 
09        -- more code here but that is irrelevant.
10 
11    end

Well, I hope I helped and have a nice day/night.

Thanks,

Best regards,

~~ KingLoneCat

Answer this question