I use RunService, but I need to get the Character (when it gets added first time and when respawn).
I put a RunService.Heartbeat event inside a CharacterAdded event, but when the Humanoid.Died event is launched. It disconnects the RunService event. Will it disconnect only for the player that died or every single player in the game? I want it to be disconnected only for the player that died THEN it reconnects (because of the CharacterAdded event). Is it fine?
I simplified my script (remove the unrelated parts of code)
plr.CharacterAdded:Connect(function(character)
local RunServiceEvent = game:GetService("RunService").Heartbeat:Connect(function()
task.wait(5)
print(character.Name," run service ran")
end)
local Humanoid = character:FindFirstChildWhichIsA("Humanoid")
Humanoid.Died:Connect(function()
print(character.Name, "run service stopped")
RunServiceEvent:Disconnect()
end)
end)
Yes this will work, however I recommend using only one event and looping over the players to do what you need to do.
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- We'll use this so we don't have to call Players:GetPlayers() every heartbeat.
local playersTable = Players:GetPlayers()
Players.PlayerAdded:Connect(function(player)
table.insert(playersTable, player)
end)
Players.PlayerRemoving:Connect(function(player)
local i = table.find(player)
if i then
table.remove(playersTable, i)
end
end)
local function isPlayerAlive(player: Player): boolean
return player.Character and player.Character.Parent
end
RunService.Heartbeat:Connect(function()
for _, player in playersTable do
if not isPlayerAlive(player) then
continue
end
-- Do your thing.
end
end)
If you need to do heavy computations for each player, you could consider using Parallel Luau with :ConnectParallel (your script must have an Actor ancestor somewhere) and stick with your design of using 1 connection per player*.
*Do keep in mind that if you get a single-core server instance, heavy usage of parallel Luau can suffer greatly.