Hello, I’m trying to execute some code (on the server) when a player changes his team.
I’m using this code:
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print("Player changed team")
-- Executing code here...
But will this code not cause a memory leak? I’ve looked on the forum and from what I’ve read Players don’t get “:Destroy()”-ed when they leave. So the connection would still be active when the specified Player left the game? Would there be a better way to know if a Player changed it’s team? (preferably without RemoteEvents)
As much as I know, that code won’t cause any kind of Memory leaks but I have a feeling you should connect it when a player joins instead of running a loop through all players.
Also as said on the Devhub API, you might want to Disconnect the connection is its necessary but in this case when player leaves the player instance is deleted so the Connection is disconnected automatically.
Yes, they do get disconnected because whenever a player leaves, the parent of that player is set to nil or in other ways, the player object is destroyed.
Your code won’t cause a memory leak but wouldn’t work for new players either since you only loop once.
A better way to know if a player changed their team is to use the PlayerAdded event, that way the code will work for everyone. However there is still 1 drawback. If the code executes really late when there are still players in the server, it would only count for new players. It’s better to have a function and run that function for every player ( looping ).
Thanks for your quick replies @Dolphin_Worm, @WaterJamesPlough and @SilentsReplacement.
I also thought connections on a player would be destroyed when they left, but I found some topics that say the contrary. They are kind of old but I think still relevant?
Also I want it so that only the players in-game at that moment get a connection. So using PlayerAdded isn’t the right solution here.