function CreateChainLightning(source, target, damage, aoe, duration, interval, bounces, attacktype, damagetype, lightning, effect, attach, rebounce)
local player = GetOwningPlayer(source)
local group = GetEnemyUnitsInRange(player, GetUnitX(target), GetUnitY(target), aoe, false, false)
if BlzGroupGetSize(group) == 1 then
DestroyLightningTimed(AddLightningEx(lightning, true, GetUnitX(source), GetUnitY(source), GetUnitZ(source) + 60.0, GetUnitX(target), GetUnitY(target), GetUnitZ(target) + 60.0), duration)
DestroyEffect(AddSpecialEffectTarget(effect, target, attach))
UnitDamageTarget(source, target, damage, false, false, attacktype, damagetype, nil)
DestroyGroup(group)
else
local timer = CreateTimer()
local damaged = CreateGroup()
local prev = nil
local this = target
local next = nil
GroupRemoveUnit(group, this)
GroupAddUnit(damaged, this)
UnitDamageTarget(source, this, damage, false, false, attacktype, damagetype, nil)
DestroyEffect(AddSpecialEffectTarget(effect, this, attach))
TimerStart(timer, interval, true, function()
DestroyGroup(group)
if bounces > 0 then
group = GetEnemyUnitsInRange(player, GetUnitX(this), GetUnitY(this), aoe, false, false)
GroupRemoveUnit(group, this)
if not rebounce then
BlzGroupRemoveGroupFast(damaged, group)
end
if BlzGroupGetSize(group) == 0 then
PauseTimer(timer)
DestroyTimer(timer)
DestroyGroup(group)
DestroyGroup(damaged)
else
next = GetClosestUnitGroup(GetUnitX(this), GetUnitY(this), group)
if next == prev and BlzGroupGetSize(group) > 1 then
GroupRemoveUnit(group, prev)
next = GetClosestUnitGroup(GetUnitX(this), GetUnitY(this), group)
end
if next then
DestroyLightningTimed(AddLightningEx(lightning, true, GetUnitX(this), GetUnitY(this), GetUnitZ(this) + 60.0, GetUnitX(next), GetUnitY(next), GetUnitZ(next) + 60.0), duration)
DestroyEffect(AddSpecialEffectTarget(effect, next, attach))
GroupAddUnit(damaged, next)
UnitDamageTarget(source, next, damage, false, false, attacktype, damagetype, nil)
DestroyGroup(group)
prev = this
this = next
next = nil
else
PauseTimer(timer)
DestroyTimer(timer)
DestroyGroup(group)
DestroyGroup(damaged)
end
end
else
PauseTimer(timer)
DestroyTimer(timer)
DestroyGroup(group)
DestroyGroup(damaged)
end
bounces = bounces - 1
end)
end
DestroyGroup(group)
end