Explosions in Unity

How to make an explosion in Unity

In Visuals by John FrenchPublished Updated 4 Comments

An explosion is a fairly common effect in video games.

It can be implemented in a number of different ways, using a number of different techniques.

However, while there are many ways you could make an explosion, generally speaking, they typically all involve three main elements.

A physical application of force, a visual effect and the potential to cause damage to other objects.

But…

While the general idea of making an explosion in Unity may seem relatively straightforward, actually creating one can be a little more complicated.

This is because there isn’t a way to passively apply force to other objects in your scene.

Instead, you’ll need to get a reference to every object that’s going to be affected by the explosion and move each one yourself, manually.

In this article, you’ll learn how to create an explosive force using the 3D and 2D physics systems, how to create a basic visual effect using particles and how to apply damage to objects that are inside the blast radius.

So, how does it all work?

How to make an explosion using 3D physics

Unfortunately, it’s not possible to simply create an explosion in your scene that automatically affects physics objects around it.

Instead, you’ll need to directly apply a physical force to each object that’s within the explosion’s radius.

However, while it may not be possible to create a passive explosion effect in Unity, there is a built-in function for applying explosive force to an object’s rigidbody, once you have a reference to it.

So how can you get a reference to all of the objects inside an explosion’s area of effect?

Explosion in Unity using 3D physics

One method is to use an Overlap Sphere.

Overlap is a physics function that finds colliders that are inside of or touching a specific area, in this case a sphere, specified by a point of origin and a radius.

It typically returns an array of colliders that were found when the function was called.

Like this:

Collider[] hitColliders = Physics.OverlapSphere(center, radius);

While this works, this method creates a new array each time, which can cause garbage.

Which, if you’re calling the function constantly, by repeatedly setting off explosions, for example, can affect performance.

Instead, the non-allocating version of overlap sphere, Overlap Sphere Non Alloc, can be much more efficient as, instead of building a new array each time, it fills up an existing one, like a buffer, and returns the number of colliders that were found instead.

Like this:

Collider[] colliders = new Collider[20];
[SerializeField] LayerMask layerMask;

void ExplodeNonAlloc()
{
    int numColliders = Physics.OverlapSphereNonAlloc(transform.position, explosionRadius, colliders, layerMask);

    if (numColliders > 0)
    {
        for (int i = 0; i < numColliders; i++)
        {
            // Apply force to each collider.
        }
    }
}

When using this method, you’ll only be able to detect as many colliders as the array can hold, meaning that you’ll want to create an array big enough to store the maximum number of objects that you want your explosion to be able to affect.

It’s also a good idea to use a Layer Mask to filter out colliders that you know shouldn’t be affected by the explosion.

This will help to avoid creating references to colliders that you don’t intend to move, saving performance.

Once you have a reference to each collider, you’ll be able to apply an amount of force to move it.

For this to work, the object will need to have a Rigidbody component attached to it, which is what allows an object to be moved under physics simulation.

It’s possible to check if the object that’s associated with the detected collider has a rigidbody, and get a reference to it if it does, by using Try Get Component, which only returns true if a component of a specific type is found.

Then, if one is, the reference that’s created can be used to apply an explosive force to that object by using the Add Explosion Force function, and by passing in a vector 3 position and radius to determine the area of effect, which will typically be the same values used to detect the colliders in the first place.

Like this:

public class Explosion : MonoBehaviour
{
    [SerializeField] float explosionForce = 10;
    [SerializeField] float explosionRadius = 10;
    Collider[] colliders = new Collider[20];

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ExplodeNonAlloc();
        }
    }

    void ExplodeNonAlloc()
    {
        int numColliders = Physics.OverlapSphereNonAlloc(transform.position, explosionRadius, colliders);

        if (numColliders > 0)
        {
            for (int i = 0; i < numColliders; i++)
            {
                if (colliders[i].TryGetComponent(out Rigidbody rb))
                {
                    rb.AddExplosionForce(explosionForce, transform.position, explosionRadius);
                }
            }
        }
    }
}

The Add Explosion Force function applies a variable amount of force automatically, where objects that are further away from the centre of the explosion are moved less than the objects that are closer.

It’s also possible to adjust the direction of the force that’s applied by using the optional Upwards Modifier parameter, which moves the position of the force that’s applied as if it’s coming from underneath the object.

Like this:

// Adjusts the direction of the force applied so that it's 3 units lower.
rb.AddExplosionForce(explosionForce, transform.position, explosionRadius, 3);

This can make explosions more dramatic and more realistic, as objects will jump up slightly and will be more likely to be bounced around, instead of just sliding along the floor.

How to make an explosion effect (using particles)

There are many different ways that you could make the visual effect of an explosion in Unity, and exactly how you do it will, no doubt, be influenced by the visual style of your game.

However, a simple method is to use a Particle System component.

But, while, the particle system is generally easy to work with, it can be slightly unintuitive if you haven’t used it before.

To create an explosion-style particle effect, you’ll need to change the Shape of the emitter to a sphere, lower the Particle Lifetime value to something short, so that particles quickly die after being created, and change the Rate Over Time to zero.

This last step is important, as it allows you to create a burst emission instead of a continuously created stream of particles.

Particle System Settings for creating an explosion effect

Finally, disable Looping and Play the particle effect whenever the explosion is required.

Like this:

[SerializeField] ParticleSystem explosionEffect;

void Explode()
{
    explosionEffect.Play();
}

You can then apply your own particle material, and by adjusting the size, colour or rotation of the particle over time, you can create an explosion effect that you like the look of.

Or, if you’d rather get professional results quickly, the Unity Asset Store provides ready-made options for both realistic and cartoon explosion and fire effects.

The Add Explosion Force function is ideal for creating explosive physics in 3D, as it calculates the roll-off of a blast’s effect against other objects for you, automatically.

However, the 3D and 2D physics systems in Unity are separate, and there is no equivalent Add Explosion Force function in 2D.

So how can you make an explosion in Unity in 2D?

How to make an explosion using 2D physics

Unlike when using the 3D physics engine in Unity, there’s no built-in method to apply an explosive force in 2D.

Meaning that, if you want to create a 2D explosion that affects objects around it, you’re going to have to move them yourself.

This works in a similar way to the 3D method, where you’ll need to get a reference to the colliders that you want to be affected first, typically by using an overlap method, such as Overlap Circle.

Like this:

public class ExplosionForce : MonoBehaviour
{
    [SerializeField] float radius = 10;
    [SerializeField] float force = 100;
    [SerializeField] ContactFilter2D contactFilter;
    [SerializeField] Collider2D[] affectedColliders = new Collider2D[25];

    void Explode()
    {
        int numColliders = Physics2D.OverlapCircle(transform.position, radius, contactFilter, affectedColliders);

        if (numColliders > 0)
        {
            for (int i = 0; i < numColliders; i++)
            {
                if (affectedColliders[i].gameObject.TryGetComponent(out Rigidbody2D rb))
                {
                    // Apply force to the object
                }
            }
        }
    }
}

You’ll then need to calculate your own explosion force.

This is where the 2D and 3D methods are different, as there’s no existing function to calculate the direction and roll-off of force that needs to be applied.

Instead, this can be done by getting a direction between the origin of the explosion and the position of the object.

Like this:

Vector3 forceDirection = rb.transform.position - transform.position;

Then, by calculating a Distance Modifier, which is a value between zero and one that represents the object’s position from the centre of the blast (1) and the edge (0), you’ll be able to scale the force that’s applied to each object depending on how far away it is from the explosion.

Like this:

Vector3 forceDirection = rb.transform.position - transform.position;
float distanceModifier = 1 - (Mathf.Clamp(forceDirection.magnitude, 0, radius) / radius);

Clamping the value to the limits of the explosion radius prevents negative values when the object is touching the area of effect but is actually further away than the maximum radius.

The force can then be applied at a position on the object, instead of its centre.

Explosion in Unity using 2D physics

The purpose of this is to create a more natural application of movement and torque, causing the object to spin as it’s blown away.

This works by passing in the point on the collider that’s closest to the origin of the explosion.

Like this:

public class ExplosionForce : MonoBehaviour
{
    [SerializeField] float radius = 10;
    [SerializeField] float force = 100;
    [SerializeField] ContactFilter2D contactFilter;
    [SerializeField] Collider2D[] affectedColliders = new Collider2D[25];

    void Explode()
    {
        int numColliders = Physics2D.OverlapCircle(transform.position, radius, contactFilter, affectedColliders);

        if (numColliders > 0)
        {
            for (int i = 0; i < numColliders; i++)
            {
                if (affectedColliders[i].gameObject.TryGetComponent(out Rigidbody2D rb))
                {
                    Vector3 forceDirection = rb.transform.position - transform.position;
                    float distanceModifier = 1 - (Mathf.Clamp(forceDirection.magnitude, 0, radius) / radius);

                    Vector2 forcePosition = affectedColliders[i].ClosestPoint(transform.position);
                    rb.AddForceAtPosition((forceDirection * force) * distanceModifier, forcePosition);
                }
            }
        }
    }
}

How to damage objects with an explosion

There are a couple of different ways to allow an explosion to cause damage to objects around it.

Generally, it involves checking for a particular type of component on each object that it hits.

How you do this depends on the structure of your game, but you might typically use Try Get Component to find a script that allows an object to take damage.

Like this:

if (affectedColliders[i].gameObject.TryGetComponent(out Damageable damageable))
{
    damageable.TakeDamage(100 * distanceModifier);
}

Or you might use something like an Interface to allow different types of script to be treated in the same way, even if each one responds to the explosion damage differently.

Now it’s your turn

Now I want to hear from you.

How are you creating explosions in your game?

Are you using physics to move objects around or something else?

And what have you learned about blowing things up in Unity that you know someone else would find useful?

Whatever it is, let me know by leaving a comment.

John French profile picture

by John French

Game audio professional and a keen amateur developer.

Get Game Development Tips, Straight to Your inbox

Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.

How to CODE in Unity. Available to Pre Order Now. Game Dev Beginner.

Image attribution

Comments

  1. Hello, i am newbie.
    What do you think about the topic “moving object on the wall” like a spider moving on the wall without the effect of gravity?

    1. Author

      For an article? I think that it would mostly be covered by other articles I’ve written, such as my movement article, but I’ll look into it.

  2. hi i am trying to make a selective explosion over the layermask. Explosions only affect enemy targets and can take damage. However, when applied, the amount of damage is multiplied many times by traversing each element of the array. It seems that taking this damage will call all the damageable objects

Leave a Comment