public GameObject explosionEffect;
public float delay = 3f;
public int damageAmount = 80;
public float explosionForce = 10f;
public float radius = 20f;
public void Start()
{
Invoke("Explode", delay);
}
public void Explode()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
foreach (Collider near in colliders)
{
Rigidbody rig = near.GetComponent<Rigidbody>();
if (rig != null)
rig.AddExplosionForce(explosionForce, transform.position, radius, 1f, ForceMode.Impulse);
}
Instantiate(explosionEffect, transform.position, transform.rotation);
Destroy(gameObject);
}
private void OnTriggerEnter(Collider other)
{
PlayerHealth player = other.GetComponent<PlayerHealth>();
if (player != null)
{
player.AlterHealth(-damageAmount);
}
enemyHealth enemy = other.GetComponent<enemyHealth>();
if (enemy != null)
{
enemy.AlterHealth(-damageAmount);
}
}
}
public void Explode()
{
Collider colliders = Physics.OverlapSphere(transform.position, radius);
foreach (Collider near in colliders)
{
Blow(near);
Damage(near);
}
Instantiate(explosionEffect, transform.position, transform.rotation);
Destroy(gameObject);
}
private void Blow(Collider other)
{
Rigidbody rig = near.GetComponent<Rigidbody>();
if (rig != null)
rig.AddExplosionForce(explosionForce, transform.position, radius, 1f, ForceMode.Impulse);
}
private void Damage(Collider other)
{
PlayerHealth player = other.GetComponent<PlayerHealth>();
if (player != null)
player.AlterHealth(-damageAmount);
enemyHealth enemy = other.GetComponent<enemyHealth>();
if (enemy != null)
enemy.AlterHealth(-damageAmount);
}
I assume you want everyone in the radius to be affected, in that case you should apply the damage in the Explode method. If players only have 1 collider, then you can just apply the damage where you use AddExplosionForce.
If players have multiple colliders, add the already affected Rigidbodies to a List (because most likely you only want to affect all players once instead of the number of colliders they have).
Solution with multiple colliders (it works with a single collider too):
public void Explode()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
List<Rigidbody> affectedRigs = new List<Rigidbody>();
foreach (Collider near in colliders)
{
//I recommend using attachedRigidbody instead of GetComponent because
//it finds the Rigidbody even if it's among the parent objects
Rigidbody rig = near.attachedRigidbody;
if (rig != null && !affectedRigs.Contains(rig))
{
rig.AddExplosionForce(explosionForce, transform.position, radius, 1f, ForceMode.Impulse);
PlayerHealth player = rig.GetComponent<PlayerHealth>();
if (player != null)
{
player.AlterHealth(-damageAmount);
}
affectedRigs.Add(rig);
}
}
Instantiate(explosionEffect, transform.position, transform.rotation);
Destroy(gameObject);
}