user7152599
user7152599

Reputation:

Object destroys and doesnt play particle system

I'm new to scripting in unity and I have a script that destroys an object when its health reaches 0

var EnemyHealth : int = 10;

function DeductPoints (DamageAmount : int) {
    EnemyHealth -= DamageAmount;
}

function Update () {

    if (EnemyHealth <= 0) {
        GetComponent.<ParticleSystem>().Play();
        Destroy(gameObject);
    }
}

When I run this script it works fine but when it gets destroyed, it doesn't play the animation and continues with destroying it.

Upvotes: 1

Views: 3186

Answers (1)

Hellium
Hellium

Reputation: 7346

How a particle system is supposed to play if you destroy the object holding it ?

Instantiate a prefab of the particle system with an auto-destrut parameter and do not make it a child of the object to destroy.

 if (EnemyHealth <= 0) {
    Instantiate( particlesPrefab, transform.position, transform.rotation ) ;
    Destroy(gameObject);
}

Edit : I thought particles systems had a parameter to destroy automatically themselves at the end of the emission but I can't find it. You may have to add a script to the prefab holding the particles system so as to destroy it after a given delay using the 2nd parameter of the Destroy function.

private void Start()
{
    ParticleSystem ps = GetComponent<ParticleSystem>();
    Destroy( gameobject, ps.main.duration ) ;
} 

Upvotes: 2

Related Questions