Search Unity

How can i play a particle effect after my gameobject has been destroyed?

Discussion in 'Scripting' started by brunoenvia, Nov 15, 2019.

  1. brunoenvia

    brunoenvia

    Joined:
    Aug 5, 2019
    Posts:
    94
    i have this explosion particle effect childed to a gameobject but when i destroy the gameobject
    the particle effect is destroyed too, is there a way i can play the particle effect at the same time it's destroyed?
    this is how my code looks like at the moment

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerDeath : MonoBehaviour
    6. {
    7.     [SerializeField] Collider[] deathCollider = new Collider[2];  
    8.     [SerializeField] GameObject ball;
    9.     [SerializeField] ParticleSystem deathVFX;
    10.  
    11.     private void Awake()
    12.     {
    13.         deathVFX.Stop();
    14.     }
    15.  
    16.     // Start is called before the first frame update
    17.     void Start()
    18.     {
    19.        
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void Update()
    24.     {
    25.        
    26.     }
    27.  
    28.     public void OnTriggerEnter(Collider deathCollider)
    29.     {
    30.         Instantiate(deathVFX, transform.position, transform.rotation);
    31.         // deathVFX.Play();
    32.         Destroy(ball);
    33.     }
    34. }
    35.  
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You have to unparent the particle effect's GameObject before the parent is destroyed.
     
    Joe-Censored likes this.
  3. Team2Studio

    Team2Studio

    Joined:
    Sep 23, 2015
    Posts:
    98
    Or you could remove the parenting completely, and create a pool of particle effects.
    Each time a GameObject gets destroyed, pick a particle effect from the pool and set it's position
    to the position of the destroyed GameObject and let it play its magic. When it's done, reset it in the pool.
    This way, a lot of GameObjects get saved from instantiating and destroying, which is bad for performance.
     
    Joe-Censored likes this.
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Yep, somehow make the particle effect a separate object. You could unparent or pull one from a pool as stated above, or you could instantiate/destroy it.