Using playeradded event messes up the script because 'class' goes to a different player that just joined. I've tried changed, descendent removed and added, but nothings working for me.
01 | game.Players.PlayerAdded:connect( function (player) |
02 | local touched = false |
03 | local function ontouch() |
04 | if not touched then |
05 | touched = true |
06 | local class = game.ReplicatedStorage [ "Class #1" ] :Clone() |
07 | class.Parent = player.Character |
08 | end |
09 | end |
10 | script.Parent.Touched:Connect(ontouch) |
11 | end ) |
What you normally would need is GetPlayerFromCharacter()
function. However since you are parenting the class to a character, you do not need to know player at all. You should however make sure that it was a character that touched your part and not some random brick.
01 | local touched = false |
02 | local function ontouch(hit) |
03 | local character = hit.Parent |
04 | if not touched and character:FindFirstChild( "HumanoidRootPart" ) then |
05 | touched = true |
06 | local class = game.ReplicatedStorage [ "Class #1" ] :Clone() |
07 | class.Parent = character |
08 | end |
09 | end |
10 | script.Parent.Touched:Connect(ontouch) |
On a side note, you should keep your assets in the ServerStorage instead of the ReplicatedStorage. That is an obsolete and unnecessary practice from FE disabled times. Unused assets do not need to be replicated to clients, to reduce transfer.
Using a touch event you could get the player from their character using the function:
1 | :GetPlayerFromCharacter() |
This function takes the given parameter (Whatever is inside of the parenthesis), and if the given object is a players character model, then it is able to get the player from said characters model.
Here is an example of it in action:
1 | script.Parent.Touched:connect( function (hit) |
2 | if game.Players:GetPlayerFromCharacter(hit.Parent) then |
3 | local plr = game.Players:GetPlayerFromCharacter(hit.Parent) |
4 | print (plr.Name) |
5 | end |
6 | end ) |
Here is a link to the wiki article:
https://developer.roblox.com/en-us/api-reference/function/Players/GetPlayerFromCharacter