Hi all. I am working on a simple game where the player shoots as a tank at targets. There I have explosions happening when projectile hits other objects - targets or ground. Since I want my explosions to be visible(and epic), Iam instantiating an ParticleSystem every time I need an explosion to occur. I have two scripts involved in explosions. They are:
using UnityEngine;
using System.Collections;
public class ProjectileExplosion : MonoBehaviour {
public float explosionForce = 5.0f;
public float explosionRadius = 5.0f;
private ExplosionHandler explosionHandler;
private Vector3 explosionCoords;
void OnCollisionEnter(Collision collision){
explosionHandler = GameObject.FindObjectOfType<ExplosionHandler>();
explosionCoords = collision.contacts[0].point;
Collider[] colliders = Physics.OverlapSphere(explosionCoords, explosionRadius);
explosionCoords.y+=1.5f;
explosionHandler.explode(explosionCoords);
foreach(Collider hitTarget in colliders){
Rigidbody rigidBody = hitTarget.GetComponent<Rigidbody>();
if(rigidBody != null){
rigidBody.AddExplosionForce(explosionForce, explosionCoords, explosionRadius, 15.0f);
}
}
Destroy(gameObject);
}
}
…and:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosionHandler : MonoBehaviour {
public ParticleSystem ps1;
public ParticleSystem ps2;
private float delay = 4.0f;
public void explode(Vector3 coords){
ParticleSystem exp1 = Instantiate(ps1, coords, ps1.transform.rotation);
ParticleSystem exp2 = Instantiate(ps2, coords, ps2.transform.rotation);
exp1.Play();
exp2.Play();
Destroy(exp1, delay);
Destroy(exp2, delay);
}
}
First script simply detects the position of the collision and sends the coordinates to the other gameobject, which recieves these coordinates, instantiates two different explosions there, plays them and then it should also destroy these ParticleSystems. First script also releases the force of the explosion and destroys the projectile(successfully).
My problem is that Iam simply unable to destroy the particle system clones after they do their part and they keep on piling up in the hierarchy window. I’ve spent hours trying to handle this but unsuccessfully, did and re-did everything, tried with tags, layers, anything I could come up with or found on Google. I just can’t get rid of them ParticleSystems. Can somebody pretty please explain to me what is the problem here that I seem to be missing? Any help, hint or example will be greatly appreciated! Thanks.