Why this script teleport everyone?

Hi, I’m doing an elevator that tp you to the floor when you press the button

It’s supposed to tp only the player that press the button, but it tp everyone :confused:

  1. I tried to use a normal and a local script, and it doesn’t work :slightly_frowning_face:
local Player = game.Players.LocalPlayer
local PlaceToTeleport = game:GetService("Workspace"):FindFirstChild("F0")

function onClicked()
local p = game.Players:GetChildren()
for i = 1, #p do
p[i].Character:MoveTo(PlaceToTeleport.Position)
end
end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

Please, help me :smiley:

1 Like

It teleports everyone because you told it to do so. MouseClick listeners get a reference to the player who clicked the click detector so use that.

script.Parent.ClickDetector.MouseClick:Connect(function(player)
    player.Character:SetPrimaryPartCFrame(PlaceToTeleport.CFrame)
end)
3 Likes

But I do it in a normal script or a local?

For this you would just use a server script

Hello there!

To start off, just wanna say that in your “onClicked” function, you’re doing a for loop iterating through the player list (game.Players:GetChildren()).

local Player = game.Players.LocalPlayer
local PlaceToTeleport = game:GetService("Workspace"):FindFirstChild("F0")

function onClicked()
    if Player.Character then
          Player.Character:MoveTo(PlaceToTeleport.Position)
    end
end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

This can be both local/server, but since you’re using the local player, and it’s based on player movement, you should use local script.

As long as it is not a local script, this should work. (to the best of my knowledge)

Actually, either. When teleporting your character, using a client would actually be beneficial, as it would result in a quicker response time and feel much smoother. However, it will work on both server and client.