If i set Moving variable to false, will it cancel thread?

Soo i have this script, it creates thread for enemy moving in tower defense game:

local Thread = task.spawn(function()
		while self.Moving do
			local Node = self.Path[self.CurrentNode]
			local NextNode = self.Path[self.CurrentNode + 1]
			if not NextNode then
				VACC:Clear(self)
				
				return
			end
			local Time = (NextNode - Node).Magnitude / self.Speed
			
			self.Position = Node:Lerp(NextNode, self.CurrentNodeTime/Time)
			self.Part.Position = self.Position
			
			self.CurrentNodeTime += task.wait(Frequency)
			if self.CurrentNodeTime > Time then
				self.CurrentNodeTime = 0
				self.CurrentNode += 1
			end
		end
		
		return
	end)

Question is, if i call Enemy:Stop() from main script, and self.Moving will be set to false, will this thread be Garbage Collected or not?

if you set self.Moving to false it will first finish it’s iteration and if you don’t have any other references to Thread it will get garbage collected

1 Like

personally; i’d have 1 function that gets called each frame that updates every enemy
but i suppose yeah; if your function ends it’d probably get garbage collected aslong as you set Thread to nil

maybe just do this:

local Thread Thread = task.spawn(function()
	[...]
	Thread = nil
	return
end)
1 Like

It will end iteration, also i don’t store reference due to strange GCollector bug with my maid class where i can’t cancel thread inside this thread, thx for help

1 Like