Script randomly errors

I have a script that randomly generates a map made of hexagonal tiles, and sometimes a loop in it errors, specifically the for i,v in ipairs(hexes) do

local function generateMap()

	repeat

		local t = {}

		for i,v in ipairs(hexes) do

			local angle = 30
			local pos = v.CFrame.Position

				for i2=1,6 do
					if hexAmount == maxHexAmount then
						break
					end
					local dir = (CFrame.new(pos)*CFrame.fromEulerAnglesXYZ(0,math.rad(angle),0)).LookVector*3.132
					local result = workspace:Raycast(pos,dir,rp)

					if not result and math.random(1,chance) == 1 then

						hexClone = hexTile:Clone()
						hexClone.Parent = map
						hexClone.CFrame = CFrame.new(pos+dir)
						table.insert(t,hexClone)
						hexAmount += 1

					end

					angle += 60

				end

			if i % 5 == 0 then task.wait() end

		end

		if #t > 0 then
			hexes = t
		end

	until hexAmount >= maxHexAmount
end

add a task.wait(.05) in all of the loops.
this adds some execution time, and does not force the script to execute fast

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