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 4 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.

game.Players.PlayerAdded:connect(function(player)
    local touched = false
local function ontouch()
    if not touched then
    touched = true
local class = game.ReplicatedStorage["Class #1"]:Clone()
class.Parent = player.Character
    end
end
script.Parent.Touched:Connect(ontouch)
end)

2 answers

Log in to vote
0
Answered by
sleazel 1287 Moderation Voter
4 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.

local touched = false
local function ontouch(hit)
    local character = hit.Parent
    if not touched and character:FindFirstChild("HumanoidRootPart") then
        touched = true
        local class = game.ReplicatedStorage["Class #1"]:Clone()
        class.Parent = character
    end
end
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.

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

Using a touch event you could get the player from their character using the function:

: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:

script.Parent.Touched:connect(function(hit)
    if game.Players:GetPlayerFromCharacter(hit.Parent) then
        local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
        print(plr.Name) 
    end
end)

Here is a link to the wiki article:

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

Answer this question