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

How do i get the player from a normal script?

Asked by 5 years ago

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.

01game.Players.PlayerAdded:connect(function(player)
02    local touched = false
03local function ontouch()
04    if not touched then
05    touched = true
06local class = game.ReplicatedStorage["Class #1"]:Clone()
07class.Parent = player.Character
08    end
09end
10script.Parent.Touched:Connect(ontouch)
11end)

2 answers

Log in to vote
0
Answered by
sleazel 1287 Moderation Voter
5 years ago

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.

01local touched = false
02local 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
09end
10script.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.

Ad
Log in to vote
0
Answered by
BuDeep 214 Moderation Voter
5 years ago

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:

1script.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
6end)

Here is a link to the wiki article:

https://developer.roblox.com/en-us/api-reference/function/Players/GetPlayerFromCharacter

Answer this question