How to add explosion effect after the player gets destroyed

i have downloaded particle effects from unity and imported it to unity but how to add it to the player and add explosion when the player gets destroyed

Hi Pramo,

You could try the following;

  • prefab your explosion GameObject if you haven’t already

  • in the script which needs it’s GameObject to exploder (Player.cs?), add a member variable (field) which will hold a reference to the prefab;

    private GameObject explosionPrefab;
    
  • within the Inspector, drag your prefab into this exposed field

  • in your code which currently handles the detection, most likely OnCollisionEnter, add something like this;

    private void OnCollisionEnter(Collision collision)
    {
        Instantiate(exploisionPrefab, gameObject.transform.position, Quaternion.identity);
    
        // other code which destroys the player
    }
    

The above will create a new GameObject, a clone of your prefab and position it at the player’s position.

Note, I’m assuming in the above that the particle effects on the explosion prefab are set to play automatically. Also, it is good practice to have an empty GameObject which you use as a parent for these kinds of instantiated objects.

Also, you will most likely want to Destroy the explosion GameObject after it has run its particle effect.

Hope this helps :slight_smile:


See also;

I’m sry… I’m don’t have that much knowledge in c# or unity I’m a beginner.so don’t mind if I say anything wrong
My gameobject to be explode is player and I have its prefab… Now do I need to add these two scripts in my player collider script or I need to create a new script.im sry I can’t understand.i don’t even know how to add the asset(particle effect)I downloaded to my player

Okay so let’s take a step back. Using your particle system asset(s):

1a. In your Hierarchy tab, you can right-click and select Effects… Particle System.
or 1b. Again in Hierarchy, right-click, Create Empty. Select the empty Game Object; in the Inspector, click add component and select Particle System.

  1. Okay, so now you have a particle system to play with. You should probably set it’s transform to Origin (0,0,0) to prevent possible future unexpected results.

  2. Now, if you double-click the GameObject in the Hierarchy it will centre it in the Scene view, allowing you to see it while you tweak it.

  3. I’m not really going to go into what to do over in the inspector. Ther is a LOT that can be done with particle systems. Try YouTubing some tutorials, is my suggestion.

      1. Setup the particle system game object the way that makes you happy…
  4. When you are happy with the particle system: be sure it has a meaningful name in the Hierarchy.

  5. Make it a ‘prefab’ (i.e. drag it from the Hierarchy into the Project tab and it will make a prefab in the Project tab for you.)

  6. From here, you can go back and look at what Rob has told you. If it doesn’t make sense, I’d say put your idea on hold and continue the course; you’ll get to a point where it will begin to make sense to you if you keep going through the course material.

1 Like

I think Pramo mave already have some downloads Particle Effects assets, if so Pramo, these are likely to be Prefabs already in your Assets folder. You can always take a screenshot and pop it up, we might be able to confirm (make sure you expand down into any nested folders so we can see the contents though).

As we’ve already worked through the process of you hiding/destroying your player GameObject when they collider, for now, you could place the instantiation of the Prefab for the explosion particle effects in the same place (just for now). This would be in the OnCollisionEnter method where you destroy your player. So you can take the example line of code I gave you above and use that.

I’m trying to remember back, I think you had multiple scripts, one was called Player.cs and you also had PlayerMovements.cs and PlayerCollision.cs. If this is still the case, create the variable for the prefab in your PlayerCollision.cs script (for now). Then select your Player in the Hierarchy and you’ll see that the field you have added “explosionPrefab” is shown in the Inspector for the Player Collision script component. Drag your explosion prefab from the Assets folder into that field.

Take note of Jack’s comment above regarding the transform position. Hopefully, the prefabs you already have for the explosions are already 0, 0, 0. If they are not, bear in mind that they will end up being offset from the position at which you instantiate them.

Run your game and see what happens. What I would expect to happen is this;

  • you move your player’s avatar and crash it into a cube
  • a new GameObject appears in the Hierarchy which is a clone of your explosion prefab
  • it will (hopefully) play by default and you’ll biefly see this before your other scripts respawn the player to the start of the track
  • you will be left with a GameObject in your Hierarchy that you’ll want to remove which was the explosion (it may continue playing depending on the loop settings)

For testing, I’d suggest crashing into one of the closest cubes, that way when your player respawns you’ll still be able to see the explosion.

If you can get this far then I have a few other suggestions for you which will improve the experience for the player and also tidy things up, but lets see if you can get to this bit first and then go from there.

As Jack says, explosions and instantiation of prefabs are covered in the course, I’m not sure if you are even taking the course as I know this is your own game not a course one. Let us know :slight_smile:

Screenshot%20(11)

using UnityEngine;

public class PlayerCollision : MonoBehaviour {

    public PlayerMovement movement;
    public GameObject explosionprefab;

    void OnCollisionEnter(Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;

            Debug.Log("player hit");

            FindObjectOfType<GameManager>().EndGame();
            FindObjectOfType<Audiomanager>().play("playerdeath");

            Instantiate(explosionprefab, gameObject.transform.position, Quaternion.identity);

            Destroy(gameObject); 
        }
    }
}

instantiated in playercollsion script as explosionprefab which i want to explode on colliding and dragged my prefab of effect which i downloaded…but when i collide player is not exploding and explosion appears when it respawns that too less than a second

Help me Rob😅

Hi,

Can you share your project files again so I can take a look, you working copy, with the problem you have described included.

https://drive.google.com/file/d/1hL3O6CK5YxEeVX5ZmvEoVcpJdduAv4jv/view?usp=drivesdk

My explosion appears only after respawning and not at the moment the player gets destroyed… Explosion effect I used is from creepy_cat…

Will take a look for you now :slight_smile:


Updated Sat Oct 27 2018 11:23

Your project seems to contain a few example things and one of them is causing an error;

Assets/_Creepy_Cat/3D Games Effects Pack Free/Example_02/InstanceExample.cs(13,9): error CS1070: The type `UnityEngine.ParticleSystem’ has been forwarded to an assembly that is not referenced. Enable the built in package ‘Particle System’ in the Package Manager window to fix this error.

Is this something you see also?


Updated Sat Oct 27 2018 11:29

I’m getting error after error after error here, appears to be numerous reference issues with the project.


Updated Sat Oct 27 2018 11:34

image

Which one of these solutions is the one you are working with?


Updated Sat Oct 27 2018 11:41

I don’t think this is a copy of your working project, as the Project Settings\ProjectVersion.txt is blank, typically this contains the version number of the Unity which opened the project last.

Can you try again with providing me with a working copy of the project. Cheers.


Updated Sat Oct 27 2018 12:20

Ok, I’ve rebuilt your project and can now run it without error. yay!

I’m not actually seeing any explosions at all, which scene were you specifically testing this behaviour in?


Updated Sat Oct 27 2018 12:35

Looking at your PlayerCollision.cs script I don’t see anything in here, or the other scripts, which imply there’s anything being done to instantiate the explosions Pramo? Again, if you have a version I can look at that shows what you are doing to try to achieve this I would be grateful.

I’m having my original game… I don’t want to make any mistakes and do the whole thing again so I took a copy of that and I’m working on it… Yes test game 1 is the one I’m working on. It was a bit confusing on which explosion should I add so I imported few.but I’m using that “creepy_cat” it also shows me warning but I’d clear it and it does not shows up again.sorry Rob I’ll check it and send you again

Check this Rob
https://drive.google.com/file/d/1iq_U7pvNWChC01GFNVUt51i-D_eF8O-J/view?usp=drivesdk

Sorry for the mistake… Instead of 2 I send you 1… Just to be aware not to make mistake in original project.
When you hit play u can see explosion appears at the time if respawning. I thought to add materials to my player and ground so imported few assets btw it’s showing parsing error I don’t know how to clear it.sorry for late reply

Hey,

Ok, so what you have provided here again has issues. Opening the project displays an error with regards to the Creepy Cat example02.cs script, there’s no issue with the code, there are issues with the references within the project. I commented out all of the code in this example and then all of your scripts error also, any references to the Unity API generate errors.

Is this actually your working copy of your project, or did you create a folder with the various parts you thought I may need? If it is a direct copy of your project I would recommend that you create a new empty project, import your assets and then save the project, using the new one as the working copy going forward.

Having taken the above steps I am able to at least open your project in Unity and run the game.

Looking at scene 1 I see you are using effect 8. To check the particle system was ok I just dragged it into the scene, expanded the GameObject so I could see the Particle System, selected it and click Play - it looked ok.

I ran the game and I could see what you are describing, e.g. it looks like the explosion is appearing where the player respawns, but this is an illusion. If you run the game and click pause at the moment the sphere hits a cube you’ll see Effect08 (clone) is created in the Hierarchy, this is the instantiated explosion prefab, double-click on it and you will be taken to its position in the scene, as you will see, its in front of the block where the collision occurred.

You have a few other things going on here though, part of your collision code calls EndGame within GameManager.cs, and in turn, that invokes Restart after 1 second. Your Restart method, despite my previous advice, currently reloads the scene, as opposed to just re-positioning the player, as such all of the game objects in the current scene are destroyed. Occasionally, you get to see a bit of your explosion in a frame that gets caught, and it gives the appearance of it being at the player’s spawn location, but it isn’t.

To demonstrate this, comment out the following line from your OnCollisionEnter method in PlayerCollision.cs;

    {
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;

            Debug.Log("player hit");

            // FindObjectOfType<GameManager>().EndGame();

            FindObjectOfType<Audiomanager>().play("playerdeath");

            Instantiate(explosionprefab, gameObject.transform.position, Quaternion.identity);

            Destroy(gameObject);
        }
    }

Run the game now and your player will not be respawned, the level won’t reload, and if you wait long enough you’ll see the particle system, in the correct place.

In my opinion, this particle effect is far to slow for the general speed/feel of your game - being 48 seconds long.

So, part of your problem is the way you are handling the respawn, and part of the problem is the particle effect, your code to wire up the explosion is ok.

Hope this helps :slight_smile:


Updated Mon Oct 29 2018 14:04

Just to add, I grabbed another explosion asset from the Asset Store and wired it up, just to see the difference, because this one is darker it tends to show the point of explosion a little better. I also set your delayRestart variable to 3 seconds to give the explosion a little more screen time before it gets destroyed on the scene load.

The above was an older explosion asset and most things were depreacted, so I grabbed a copy of Unity’s own Particle Effects asset, this is also free, I choose the “Large Explosion” (why wouldn’t you!");

Although, the “Small Explosion” looks pretty good and perhaps fits better;

I also noted that the explosion is instantiated at the position of the player, which in one sense makes perfect sense, as its the player you are destroying, but because its the far edge of the collider on the player which makes contact with the cube, I think the explosion looks a bit too far from the cube it made contact with, especially as the cubes can be knocked backwards/over.

You could enhance this by using the point of collision instead of the player’s transform.

oid OnCollisionEnter(Collision collisionInfo)
    {

        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;

            Debug.Log("player hit");

            FindObjectOfType<GameManager>().EndGame();

            FindObjectOfType<Audiomanager>().play("playerdeath");

            Vector3 pointOfContact = collisionInfo.contacts[0].point;

            Instantiate(explosionprefab, pointOfContact, Quaternion.identity);
            //Instantiate(explosionprefab, gameObject.transform.position, Quaternion.identity);

            Destroy(gameObject);
        }
    }

In the above, I’ve commented out your original line for the instantiation and then above it you can see I get the point of contact by taking the first point from the contacts array (contacts[0]). The result is that the explosion prefab is instantiated where the player and the cube collided, so in real terms, the radius of your sphere further along the track. If you run the game and then flick to scene view, move the viewport down to the edge of the first cube you can see this in action, but to illustrate;

Note, in both cases above the cube has moved back ever so slightly, but by the same amount in that frame, thus the second image has the explosion closer to the point of impact.

Note, in the above, its purely because of the timing that this seems to flow, e.g. the length of the explosion animation and the restartDelay variable in your GameManager. If you later move to a concept of respawning rather than reloading you will need to consider a few other factors, such as re-initialising the blocks, moving the player back to the beginning and so on, you would however be able to remove the coupling between the particle duration and the restartDelay.

Hope this helps :slight_smile:

OMG thank you soo much Rob for your help.u r so much involved in this can’t see many like you.btw I thought if I relocate player instead of reloading then the cube that moves on impact may change the gameplay so it could become see for player to pass obstacle if he repeatedly collides and obstacle moves away so I made to reload.added particle effect inbuilt in unity there was only one same effect I don’t know how to change it so I couldn’t select a large explosion… Can I know the effect name please and how to search for it.How to re-initialize the blocks? THANK YOU ROB🙏

Hi Pramo,

OMG thank you soo much Rob for your help

You are very welcome :slight_smile:

I thought if I relocate player instead of reloading then the cube that moves on impact may change the gameplay so it could become see for player to pass obstacle if he repeatedly collides and obstacle moves away so I made to reload.

It is an option, and in many cases makes things easier, however it can also cause side effects that you have to then deal with. Equally, changing the approach to respawn rather than reload will also make something things easier create other things you’ll have to deal with.

A respawning approach would save having to reload the scene continuously, as you are probably aware, each time a scene is reloading all of the GameObjects are destroyed and then in your case, they all get reloaded - that is fairly wasteful from a perspective of performance. It could also cause an unnecessary delay for the player should your scenes get larger (e.g. contain more GameObjects/effects).

Can I know the effect name please and how to search for it.

The name of the last particle effects I used were Unity Particle Pack .5x, the ones created by Unity Technologies. Here’s a link so you can see the images which will make them easier to find in the asset store within Unity.

How to re-initialize the blocks?

In order to create this approach you would need to be able to re-initialise everything in the scene, otherwise, the blocks that have already fallen will already be on the track, which will spoil the effect you have created, the blocks that have been collided with will have moved, which, as you rightly say, will create a different experience for the player.

I would start by considering all of the things in the scene which would need to be reset after the player collides with a block/dies, from what I can see that is;

  • the player - needs to be repositioned at the spawn/starting position
  • the blocks - need to be repositioned at their spawn/starting positions

So at the moment, the behaviour needed is the same.

With regards to the player, you could create a empty GameObject in the scene, perhaps name it PlayerSpawn, position it to where you want the player to respawn from on each occasion.

You could then add a field to one of your scripts (or create a new one), which you can expose in the Inspector and drag the PlayerSpawn GameObject in, this would create the reference. Then, when the player dies, use this field for the position to move the player back to.

With the blocks, the above approach would probably be a little overkill, although you could but it would mean duplicating the number of Block GameObjects. Instead, you could add a script to the Block prefab, again, have a field which will store the SpawnPosition of the Block. You could set these manually for each level.

When your player dies, along with calling a Respawn method for you player you would call something like InitialiseLevel which would set all of the blocks to their relevant positions.

An alternative way to do this, which, in the long-term may be better, would be to create a Block factory class, it could contain a list of transform positions and then iterate through that list, spawning Block prefabs at each of those positions. This would be the tidiest approach but would mean that it would be a little bit harder to see the Blocks in your level, from a designer’s POV.

A workaround may be to create empty GameObjects for each of those positions and then drag those into the list in the Block factory, it would then use those positions to spawn the actual block, but you would be able to see the empty GameObjects in the scene, with your designer head on etc, you could use Icons to make them visible in the scene.

With regards to the above, this would be a fairly large change in what you have already, e.g. you may take one step backwards before taking two steps forward. As such, if it were me I would probably try to tidy up what I already have first, for example, make sure all of the scripts you have are tidy and make sense, are they doing things their names suggest they do, do the method names all make sense. Consider using an empty GameObject to be the parent of other games objects, for example, your Blocks, by placing them all inside an empty GameObject 9with its position reset), perhaps named Obstacles you can then collapse this in the Hierarchy and actually see what you are working with.

Just suggestions, but this is what I would do before making the next big step in any development, shore up what you have first, and take a backup!

You haven’t responded specifically with regards to the project/solution issues I experienced, so again, I would be checking that it is ok before you make more significant changes, just to protect yourself.

Hope this helps :slight_smile:

Thanks Rob I’ll try this.yes I created a new project and imported assets to that as you told

1 Like

I will look forward to seeing your next update :slight_smile:

Privacy & Terms