hello! im trying to make a script that when a player with a certain username dies, it will kill all the other players. i tried putting in a print statement to see if the player that died was the username then it would print but it doesnt work.
script:
local event = game.ReplicatedStorage:WaitForChild("killPlrs")
--local db = false
game.Players.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(char)
if plr.Name == "targetframed" or "Player1" then
local hum:Humanoid = char:WaitForChild("Humanoid")
if hum.Health <= 0 then
print("plr has died.")
end
end
end)
end)
If statements don’t run costantly, they only run once alongside the rest of the code (in this case, your statement will run every time the player character is added)
This should work:
local event = game.ReplicatedStorage:WaitForChild("killPlrs")
--local db = false
game.Players.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(char)
if plr.Name == "targetframed" or "Player1" then
local hum:Humanoid = char:WaitForChild("Humanoid")
hum.Died:Once(function()
print("plr has died.")
end)
end
end)
end)
This was, every time the character dies we’ll run the print line.
EDIT: More performing/correct version:
local event = game.ReplicatedStorage:WaitForChild("killPlrs")
--local db = false
game.Players.PlayerAdded:Connect(function(plr)
if plr.Name == "targetframed" or plr.Name == "Player1" then
plr.CharacterAdded:Connect(function(char)
local hum:Humanoid = char:WaitForChild("Humanoid")
hum.Died:Once(function()
print("plr has died.")
end)
end
end)
end)
The connection with :Once() is made each time the character is added, hence why it’s placed inside plr.CharacterAdded.
Using :Connect() (without disconnecting istantly) would create multiple connections without deleting any of them, causing memory leaks.
u absolute wizard bro haha. i thought i need a remote event and stuff. i almost had it, just didn’t structure it properly. tysm 4 helping me out lamon, u saved me so much time.
full script:
game.Players.PlayerAdded:Connect(function(plr)
if plr.Name == "targetframed" or plr.Name == "Player1" then -- change ur username to whatever
plr.CharacterAdded:Connect(function(char)
local hum:Humanoid = char:WaitForChild("Humanoid")
hum.Died:Once(function()
print("plr has died.")
for _, plr in game.Players:GetPlayers() do
plr.Character.Humanoid.Health = 0
end
end)
end)
end
end)