Scriptname _00E_OorbayaDeathScript extends actor
{ Gavrant: _00E_OorbayaRace reuses the animations of the vanilla frost atronach, and Nicolas says that they are not exactly compatible with the oorbaya, quoting:
> And the Frost Atronach crumbles into pieces upon death
> The Oorbaya doesn't have the animation, hence the game crashes
> Maybe it doesn't anymore due to CrashFixes.dll but still, it's a gamble

That's why all oorbayas must be essential and rely on PlayDeathFX function here for actually dying.
And since _00E_EPOnDeath doesn't work for essential NPCs because it waits for them to actually die, PlayDeathFX also takes care about giving EP for killing an oorbaya.
As a bonus, PlayDeathFX adds several visual and sound effects that are not possible in OnDeath.
}

EffectShader Property AtronachUnsummonDeathFXS Auto
Sound Property _00E_NPCOorbaya_DeathM Auto
Explosion Property _00E_NPCOorbayaUnleashHeavenExplosion Auto
ImageSpaceModifier Property _00E_OorbayaPowerAttackIMOD Auto

Keyword Property BlameSpellKeyword Auto
Faction Property EPFaction Auto

Actor Property PlayerREF Auto

Int Property __Config_RewardExp Auto

Bool Property __Config_DeleteActor Auto
{creationkit.com do not recomment using self.Delete() on /www.creationkit.com on respwning/leveled actors }

Actor myKiller
Bool isDying = False


Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, bool abPowerAttack, bool abSneakAttack, bool abBashAttack, bool abHitBlocked)
	; Debug.Trace(self + ": OnHit")

	Actor newKiller = akAggressor as Actor
	if newKiller && isDying == False
		myKiller = newKiller
	EndIf
EndEvent

Event OnEnterBleedout()
	; Debug.Trace(self + ": OnEnterBleedout")
	PlayDeathFX()
EndEvent

Event OnReset()
	; Debug.Trace(self + ": OnReset")

	; Failsafe cleanup
	myKiller = None
	isDying = False
EndEvent


Function PlayDeathFX()
	If isDying
		Return
	EndIf
	isDying = True

	Bool doReceiveEP = False
	If __Config_RewardExp > 0
		doReceiveEP = (HasEffectKeyword(BlameSpellKeyword) || (myKiller && myKiller.GetFactionRank(EPFaction) >= 0))
	EndIf
	myKiller = None ; To not keep myKiller ref persistent

	SetGhost(True)
	Debug.SendAnimationEvent(self, "combatIdleStart")
	AtronachUnsummonDeathFXS.Play(self)
	int soundId = _00E_NPCOorbaya_DeathM.Play(self)
	Sound.SetInstanceVolume(soundId, 8.0)
	Utility.Wait(1)
	SetCriticalStage(CritStage_DisintegrateStart)
	PlaceAtMe(_00E_NPCOorbayaUnleashHeavenExplosion)
	_00E_OorbayaPowerAttackIMOD.Apply()

	StopCombat()

	If doReceiveEP
		Utility.Wait(0.5)
		_00E_EPHandler.GiveEP(__Config_RewardExp)
	EndIf

	If __Config_DeleteActor
		Delete()
	Else
		; As recommended in https://www.creationkit.com/index.php?title=Delete_-_ObjectReference
		SetCriticalStage(CritStage_DisintegrateEnd)
	EndIf
	
EndFunction