While True Do Loop Question

So currently in my game I have an Item Selling system. Each of my 50+ items have their own scripts that similarly model the one that is displayed below.

local RemoteEvent = game.ReplicatedStorage.ItemSold
local Cash = game.Players.LocalPlayer.Values.Cash
local Item = game.Players.LocalPlayer.Values.Chocolates
local CashName = Cash.Name
local SellingFor = 8
local N2Abbreviate = require(game:GetService("ReplicatedStorage").N2Abbreviate_Module)


while true do
	wait(15)
	if Item.Value == 0 then
		wait(40)
	end
	
	if Item.Value > 0 then
		local NumberSold = math.random(1,Item.Value)
		RemoteEvent:FireServer(Item,NumberSold,CashName,SellingFor)
		script.Parent.LastSold.Text = "Last Sold ".. NumberSold.." Boxs of Madd's Chocolates!"
		script.Parent.LastSoldAmount.Text = "+$"..N2Abbreviate.Convert(NumberSold*SellingFor,"Advanced")
	end
	wait(15)
end

This script is located within a ScreenGui under many frames. I did not know at first that While True Do loops run even after the User has exited the game. Therefore I got worried that running a ton of these for multiple players could cause my game to crash.

Does anyone have any solutions as to how to run this code without using a While True Do Loop in order to execute the same task?
or
Is this something not to worried about because it is in a ScreenGui?

I find it weird how the script runs even after the player leaves because everything inside PlayerGui disappears with the player.

You can change the condition that keeps the loop running to this:

while game.Players.LocalPlayer.Parent == game.Players do

If the player leaves, their parent will become nil, and since their parent is no longer equal to game.Players, it will now be false and the loop will not run.

1 Like

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