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

How do i find the localplayer with a touched event?[Important]

Asked by
sad_eyez 162
8 years ago

i need to know how to find the localplayer when you touch a part, cause i know i cant use:

game.Players.LocalPlayer

so if you can help me that would be great, thanks in advance.

2 answers

Log in to vote
1
Answered by 8 years ago

As LocalScripts don't work outside of the player and character, you'll need to use a normal Script.

The most efficient way to get the player from a touched event is to use GetPlayerFromCharacter, which is directed towards the character model, and uses that to find the player.

Below is an example of this in use. If a part is touched, it kicks the player.

local part = script.Parent

function onTouched(hit)
    if game.Players:GetPlayerFromCharacter(hit.Parent) then
        game.Players:GetPlayerFromCharacter(hit.Parent):Kick("Don't touch my brick.")
    end
end

part.Touched:connect(onTouched)

Hope this helped. If you have any questions or anything, feel free to ask them.

1
thanks both of you helped me sad_eyez 162 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

If you mean getting the client from a server-side script, you can't do it directly.

If possible, have a LocalScript handle the Touched event -- it will make your life easier.

If that's not an option, you still are going to need a LocalScript waiting in the client for a signal from the server Script that's handling the Touched event. This can be done by placing a RemoteEvent inside the Player (or StarterPlayer) that listens for that signal.

Server Script: inside the Part to be touched Assuming there's a RemoteEvent inside StarterPlayer called "RemoteEvent".

script.Parent.Touched:connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player then
        local remoteEvent = player:FindFirstChild("RemoteEvent") -- find the signal reciever
        if remoteEvent then
            remoteEvent:FireClient(player)
        end
    end
end)

LocalScript: inside StarterPlayerScripts

local player = game.Players.LocalPlayer
local remoteEvent = script.Parent.Parent:FindFirstChild("RemoteEvent") -- assuming this script is in PlayerScripts
remoteEvent.OnClientEvent:connect(function()
    -- now you can use `player` however you please, as this function should run when the player touches the part
end)

Answer this question