I’ve made a gun script, however I have a setting to add multiple bullets per shot
I am unsure how to use coroutines, so could someone help me with this?
(This probably isn’t the best way to do this, but if someone could tell me if there’s a better way to do this, please do.)
local function SpawnBullet()
local Bullet = Instance.new("Part", Folder)
Bullet.Color = BulletColor
Bullet.Material = Enum.Material.Neon
Bullet.CanCollide = false
Bullet.Massless = true
Bullet.Size = Vector3.new(0.25,0.25,2.5)
local Spread = CFrame.Angles(math.rad(math.random(MinSpread, MaxSpread)), math.rad(math.random(MinSpread, MaxSpread)), math.rad(math.random(MinSpread, MaxSpread)))
Bullet.CFrame = CFrame.lookAt(Gun.Barrel.Position, MousePosition)
Bullet.CFrame = Bullet.CFrame * Spread
local Velocity = Instance.new("BodyVelocity", Bullet)
Velocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
Velocity.Velocity = Bullet.CFrame.LookVector * BulletSpeed
local OnCooldown = false
Bullet.Touched:Connect(function(Hit)
if not Hit:IsDescendantOf(Character) and Hit and Hit.Parent then
local Humanoid = Hit.Parent:FindFirstChild("Humanoid")
if OnCooldown == false then
OnCooldown = true
if Humanoid then
Humanoid:TakeDamage(Damage)
end
Bullet:Destroy()
end
end
end)
local BulletSpawn = Bullet.Position
end
local Coroutine = coroutine.create(SpawnBullet)
for i = 1, BulletsPerShot do
coroutine.resume(Coroutine)
end
What you’re doing here is resuming an already created coroutine each time. This will not create a new coroutine each time. Instead, you can use task.spawn() each time.
for i = 1, BulletsPerShot do
task.spawn(SpawnBullet)
end
local function SpawnBullet()
local Bullet = Instance.new("Part", Folder)
Bullet.Color = BulletColor
Bullet.Material = Enum.Material.Neon
Bullet.CanCollide = false
Bullet.Massless = true
Bullet.Size = Vector3.new(0.25,0.25,2.5)
local Spread = CFrame.Angles(math.rad(math.random(MinSpread, MaxSpread)), math.rad(math.random(MinSpread, MaxSpread)), math.rad(math.random(MinSpread, MaxSpread)))
Bullet.CFrame = CFrame.lookAt(Gun.Barrel.Position, MousePosition)
Bullet.CFrame = Bullet.CFrame * Spread
local Velocity = Instance.new("BodyVelocity", Bullet)
Velocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
Velocity.Velocity = Bullet.CFrame.LookVector * BulletSpeed
local OnCooldown = false
Bullet.Touched:Connect(function(Hit)
if not Hit:IsDescendantOf(Character) and Hit and Hit.Parent then
local Humanoid = Hit.Parent:FindFirstChild("Humanoid")
if OnCooldown == false then
OnCooldown = true
if Humanoid then
Humanoid:TakeDamage(Damage)
end
Bullet:Destroy()
end
end
end)
local BulletSpawn = Bullet.Position
end
for i = 1, BulletsPerShot do
task.spawn(SpawnBullet)
end