Why does remote event works for all player in the server?

Here is the problem, i use remote events to make abailities, but when player trigger remote event than it go to the all players, example


-- local script in StarterCharacterScripts to trigger remote event when player press "E"

local UIS = game:GetService("UserInputService")
local events = game.ReplicatedStorage:WaitForChild("Events")
local AttackRE = events:WaitForChild("AttackEvent")

local cooldown = false
local COOLDOWN_TIME = 0
-- Initialize the last attack time and the cooldown duration

UIS.InputBegan:Connect(function(input, isTyping)
	if not isTyping then

		if not cooldown then

			cooldown = true

			if input.KeyCode == Enum.KeyCode.E then


				print("Player has press E, remote event has been triggered")

				AttackRE:FireServer()
			end

			task.wait(.38)
			cooldown = false
		end
	end
end)

-- script in ServerScriptService to kill player when Remote Event is triggered

local event = game.ReplicatedStorage:WaitForChild("Events")
local ev = event.AttackEvent

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local humanoid = char:FindFirstChild("Humanoid")
		ev.OnServerEvent:Connect(function()
			humanoid.Health = 0
		end)
	end)
end)

in this example script will kill all players in the server, but i wanna to do kill player that press “e”, please help me!

P.S.: sorry for my english

Because you are creating multiple event listeners whenever a player’s character is added and not validating whether the player who fired the remote is the one who’s scope you are currently in.

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local humanoid = char:FindFirstChild("Humanoid")
		ev.OnServerEvent:Connect(function(player)
            if player ~= plr then return end
			humanoid.Health = 0
		end)
	end)
end)

Ideally you should have a single listener to a RE

1 Like

thank you very much, you are crazy time saver!

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