Synchronised Cannon+Gun Firing

Hi, I am making an airplane that has both 1 heavy cannon and 2 light machine gun. The guns should shoot ten times a second each while the cannon shoots 2 rounds per second. However, everygun shoots 2 a second. Code:

function FireBoth(GunParent)
	while FiringGun do
		fireCannon(GunParent)
		fireMachineGun(GunParent)
	end
end
function fireCannon(GunParent)
	local Shoot = script.Parent.Shoot
	Shoot:FireServer(GunParent,FiringGun,Plane,Character,Player,Weapons)
	wait(0.5)
end
function fireMachineGun(GunParent)
	local Shoot = script.Parent.ShootM
	Shoot:FireServer(GunParent,FiringGun,Plane,Character,Player,Weapons)
	wait(0.1)
end

You can take advantage of the new coroutine.close like so:

local function FireBoth(GunParent)
    local cannonCoro = coroutine.create(function()
        while true do fireCannon(GunParent) end
    end)

    local machineGunCoro = coroutine.create(function()
        while true do fireMachineGun(GunParent) end
    end)

    task.spawn(cannonCoro)
    task.spawn(machineGunCoro)

    while FiringGun do task.wait() end

    coroutine.close(cannonCoro)
    coroutine.close(machineGunCoro)
end
1 Like

@qwertyexpert Wait, so in the eeach while loop i would put in the wait, what to put in the lat wait? Sry, Im nub lol

You don’t have to do anything with that code. If there was anything missing I would have mentioned it. task.wait() waits 1 frame.

Don’t put a wait in the loops because fireCannon and fireMachineGun already include a wait inside of them.

1 Like

@qwertyexpert THANK YOU SO MUCH YOUR THE BEST

1 Like
function FireBoth(GunParent)
	while FiringGun do
		task.spawn(function()
			for i = 1, 10 do
				task.wait(0.1)
				fireMachineGun(GunParent)
			end
		end)

		task.spawn(function()
			for i = 1, 2 do
				task.wait(0.5)
				fireMachineGun(GunParent)
			end
		end)

		task.wait(1)
	end
end

function fireCannon(GunParent)
	local Shoot = script.Parent.Shoot
	Shoot:FireServer(GunParent,FiringGun,Plane,Character,Player,Weapons)
end

function fireMachineGun(GunParent)
	local Shoot = script.Parent.ShootM
	Shoot:FireServer(GunParent,FiringGun,Plane,Character,Player,Weapons)
end

Don’t use this implementation (it uses threads when it isn’t necessary to do so).