To complete this script, you'll want to periodically apply damage to all enemies within the area of effect while the spell is active. You'll also need a reference to the enemyLayer so that you only damage objects in that layer. Here's one way to proceed:
using UnityEngine;
namespace Game.Spells
{
public class DivinePunishment : Spell
{
[SerializeField] private ParticleSystem particleSystem;
[SerializeField] private float areaSize;
[SerializeField] private float totalDuration;
[SerializeField] private float damagePerSecond;
[SerializeField] private LayerMask enemyLayer; // Reference to the layer that enemies are on.
private float damageInterval = 1f; // The time interval for applying damage.
private float damageTimer;
private float durationTimer;
public override void Init()
{
base.Init();
damageTimer = 0f;
durationTimer = 0f;
particleSystem.Play();
InvokeRepeating(nameof(ApplyDamage), 0f, damageInterval); // Start applying damage immediately.
}
// This method applies damage to all enemies in the circular area.
private void ApplyDamage()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, areaSize, enemyLayer);
foreach (Collider hitCollider in hitColliders)
{
UnitHealth unitHealth = hitCollider.GetComponent<UnitHealth>();
if (unitHealth)
{
unitHealth.TakeDamage(damagePerSecond * damageInterval);
}
}
}
private void Update()
{
// Timer to control the duration of the spell.
durationTimer += Time.deltaTime;
if (durationTimer >= totalDuration)
{
CancelInvoke(nameof(ApplyDamage)); // Stop applying damage.
particleSystem.Stop(); // Optionally stop the particle effects when done.
Destroy(gameObject, particleSystem.main.duration); // Clean up the spell object.
}
}
private void OnDestroy()
{
CancelInvoke(nameof(ApplyDamage)); // Ensure the repeating damage is stopped.
}
}
}
Explanation:
- A
LayerMask enemyLayer serialized field is added to specify which layer the enemies are on.
- The
Init() method is updated to set initial values for the timers and to begin invoking the ApplyDamage method repeatedly based on the damageInterval value.
- The
ApplyDamage() method is created to calculate and apply damage to enemies within the circular area.
- The
Update() method is used to keep track of the total duration the spell is active and to stop the damage and clean up once the duration has elapsed.
- The
OnDestroy() method is added to make sure damage is not applied after the spell object is destroyed.
Please note that the exact frequency of the damage (the damageInterval) is set to 1 second in this example. You can adjust this to suit your needs. Additionally, consider using a coroutine instead of InvokeRepeating and CancelInvoke for more control over the timing logic.