Events/Connections from previous playsessions not disconnecting

Hi! Im working on a tycoon and I found a problem with how my game handles events and connections. My games uses CollectionService to automate alot of the behaviours certain objects has. Like a door that opens when a player is nearby or a lamp that lights up when its night. A short example of what I mean:

Player A unlocks a button that spawns a bus (with the tag “Bus”). The server checks what tags the object has. It sees that it has the tag “Bus” and it will run a piece of code that makes it drive away every couple of seconds. Simple stuff and it all works amazingly for player A.

However when player A leaves the entire tycoon should ‘reset’ to their original state. However the piece of code that was run by CollectionService keeps running which causes alot of issues.

Im still learning Roblox Studio and Lua and i sadly couldnt find a way to solve this.

If you need more clarification please let me know.

Thank you for the help!

You could disconnect the connection. I’m assuming your using RenderedStepped for the movement of the bus, if that is the case you would simply disconnect it. Preferably using a module like maid or janitor could help a lot. If you want to manually do it you would do something like this:

local Connection

Connection = RunService.RenderedStepped:Connect(function()
   -- Movement
end)

-- Disconnect it when player leaves
Connection:Disconnect()
Connection = nil