I have a pool of objects that I want to emit a particle effect when its “destroyed” (disabled). I have two problems with this: I’m looking for the best way to trigger this and how to reset the particle effect for reuse when the object is enabled again.
I know I can use OnDisable() to trigger the particle emitter but this method is called when the objects are instantiated and then disabled…which also triggers the particle effects…which in part emphasizes the second problem as nothing I have tried will reset the emitter.
You were absolutely correct. This is what I came up with.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EmitOnCollisionScript : MonoBehaviour
{
// Object type we're checking collisions with
public GameObject ColissionObj;
// List of emitters to instantiate
public List<GameObject> EmittersTypes = new List<GameObject>();
// List of instantiated emitters
private List<GameObject> Emitters = new List<GameObject>();
// Use this for initialization
void Start ()
{
foreach (GameObject Type in EmittersTypes)
{
GameObject Emitter = Instantiate(Type) as GameObject;
Emitter.particleSystem.enableEmission = false;
Emitters.Add(Emitter);
}
}
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == ColissionObj.name)
{
foreach (GameObject Emitter in Emitters)
{
Emitter.transform.position = col.gameObject.transform.position;
Emitter.transform.rotation = col.gameObject.transform.rotation;
Emitter.particleSystem.enableEmission = true;
Emitter.particleSystem.Play();
}
col.gameObject.SetActive(false);
gameObject.SetActive(false);
}
}
void OnDisable()
{
foreach (GameObject Emitter in Emitters)
{
Emitter.particleSystem.time = 0;
}
}
}