RemoteEvents passing multiple players

Hey all, would appreciate some help with a really simple issue. I feel like I’m not grasping something with how RemoteEvents are supposed to work.

I have a basic client-side script that’s a child of a part, which triggers a remoteevent when touched:

script.Parent.Touched:Connect(function(hit)
    if hit.Parent ~= nil then
        game.ReplicatedStorage.LevelUpRemoteEvent:FireServer()
    end
end)

on the other side, I have a basic receiver that just prints the player’s name who touched it:

game.ReplicatedStorage.LevelUpRemoteEvent.OnServerEvent:Connect(function(player)
    print(player.DisplayName)
end)

but when I run this, even in isolation, all players in the game’s names are printed instead of just the player who touched it. Why is it passing multiple players, which seems directly contrary to how RemoteEvents are defined?

This is a LocalScript parented to a BasePart? That isn’t so good!

A LocalScript replicates to every player.

Since you have two players, the LocalScript is replicating itself to both of those players and when the .Touched event is fired, the RemoteEvent is firing from both LocalScripts.

And since the player argument passes in as default for all .OnServerEvent signals fired, it’s printing the players’ name that fired the event. In this case, it’s both players!

I would suggest running the .Touched event on the server instead of the client, but it depends on what you’re using the event for.

Hope this helps.

1 Like

This is because local scripts replicate to all clients, so when the part is touched, all the local scripts detect the touch and fire the event, no matter who touched it. Here’s how to fix it

local player = game.Players.LocalPlayer
script.Parent.Touched:Connect(function(hit)
   if not hit.Parent:FindFirstChild("Humanoid") then return end
   if game.Players:GetPlayerFromCharacter(hit.Parent) ~= player then return end
   game.ReplicatedStorage.LevelUpRemoteEvent:FireServer()
end)

One thing I do wanna know is; how did you get a local script to work in the workspace? It’s not possible to do in general…

1 Like

nothing wrong with the remote event, you’re mistakingly assuming that setting a touched event on a client would mean that only that client can fire it on touch.

This is not the case.

when touching the basepart, both clients are firing the event

2 Likes

It’s not a LocalScript, it’s a Script object set to run on Client side.

1 Like

Realized I was going about this completely wrong, and just added to my controller script to directly look for onTouched event for the brick from within the script, skipping any remote event, and that worked fine! Appreciate the help :slight_smile:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.