How to do chain damage in a Unity 3D game using C#

Chain damage is used in many video games as the second stage or upgrade to an existing damage from a weapon/spell. The concept is simple, one enemy is targeted and receives most of the damage and surrounding enemies receives some damage as well. This article will show you a few ways to create this in Unity 3d.

General idea:
At the initial target a sphere of X radius is created and all the assets within that radius are added to a list and damaged accordingly.

The set up:
A method is called when damage needs to be applied. That then creates a physics.overlapcircle with X radius at the target position. This gets an array of all the colliders in that radius and can apply damage accordingly. An example method s is below.
public void ChainDamage(Vector3 center, float radius, int enemyCount, int damageAmount, int degradeAmount)
    Collider[] allColliders = Physics.OverlapSphere(center, radius);
    // the first item in the array is your main target the next item in the array is the next closetest to the target and so on down the array.
    for (int i = 0; i < allColliders.Length; i++)
        // because hitColliders returns everything that has a collider the enemies need to be filtered.
        if (allColliders[i].gameObject.tag == "Enemy" && enemyCount > 0)
            // The enemy needs a script with a method named of your choosing in order to receive this message. 
            // "AddDamage" would be the name of the method in this case.
            allColliders[i].SendMessage("AddDamage", damageAmount);
            damageAmount -= degradeAmount; // each enemy recives less damage than the last.(If desired)

I hope this helps you!


Popular posts from this blog

How to create slowly revealed text in a Unity 3d game

Fade in and fade out Script for Unity 3d