While loop In Threads/Coroutines Stop Working For No Apparent Reason

I’ve be trying to rework a fire-spreading script that I made a few months ago, specifically with OOP, but I’ve run into a issue with one of the final parts of the script. The while loop that I’m using to spread the fire doesn’t seem to work for some reason. The really weird thing is that the loop works fine when it doesn’t have any code in it, but breaks when I put my code. The only time it seems to work is when the game I make it run too often and Roblox Studio crashes.

My code:

local FireHandler = {}
FireHandler.__index = FireHandler

function FireHandler.Ignite(obj,burningtime,range,chance)
	local self = setmetatable({
	},FireHandler)
	
	self.obj = obj
	self.burningtime = math.random(burningtime-range,burningtime+range)
	self.Spread = function()
		while self.obj.Parent ~= workspace.Burnt do
			task.wait(0.5)
			local random = math.random(1,100)
			if not (random <= chance) then return end
			for _, hit in pairs(workspace:GetPartsInPart(self.obj)) do
				local isflamable = hit.Material == Enum.Material.Wood or hit.Material == Enum.Material.WoodPlanks or hit.Parent:FindFirstChild("Humanoid")
				if isflamable and hit.Parent ~= workspace.Burnt then
					FireHandler.Ignite(hit,burningtime,range,chance)
				end
			end
		end
	end
	
	local fire = Instance.new("Fire")
	fire.Parent = obj
	
	obj.Parent = workspace.Burning
	
	local function Extinguish()
		self.obj.Fire:Destroy()
		self.obj.Anchored = false
		self.obj.Color = Color3.fromRGB(0,0,0)
		self.obj.Parent = workspace.Burnt
	end
	
	task.spawn(self.Spread)
	task.delay(burningtime,Extinguish)
	return self
end

return FireHandler

In case its note worthy, I call the function like this:

Fire.Ignite(part,burningtime,range,chance) --pretend that there are numbers and stuff

By the way, if you have any suggestions on how I should code this system, or know a better way of formatting the object, let me know. The main reason for me doing this is so try out OOP and improve my nonexistent skills, so I will take all the advice I can get. Thank you in advance :slight_smile:.

1 Like

I believe it might be the line if not (random <= chance) then return end. If the random number is higher than the chance it stops the function entirely. Instead of using return you should replace it with a continue

1 Like

You are absolutely correct. That line is causing the execution of the function to abort and return if that condition is met. In order to use a continue, the OP would have to try it and see what effect that has.

1 Like

@Maelstorm_1973 @Xronixle
Thank you both for the information! Your solutions worked :slight_smile:. Now I have to find a good way to detect parts lol.

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