ParticleSystemDestroyer.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. using Random = UnityEngine.Random;
  5. namespace UnityStandardAssets.Utility
  6. {
  7. public class ParticleSystemDestroyer : MonoBehaviour
  8. {
  9. // allows a particle system to exist for a specified duration,
  10. // then shuts off emission, and waits for all particles to expire
  11. // before destroying the gameObject
  12. public float minDuration = 8;
  13. public float maxDuration = 10;
  14. private float m_MaxLifetime;
  15. private bool m_EarlyStop;
  16. private IEnumerator Start()
  17. {
  18. var systems = GetComponentsInChildren<ParticleSystem>();
  19. // find out the maximum lifetime of any particles in this effect
  20. foreach (var system in systems)
  21. {
  22. m_MaxLifetime = Mathf.Max(system.main.startLifetime.constant, m_MaxLifetime);
  23. }
  24. // wait for random duration
  25. float stopTime = Time.time + Random.Range(minDuration, maxDuration);
  26. while (Time.time < stopTime || m_EarlyStop)
  27. {
  28. yield return null;
  29. }
  30. Debug.Log("stopping " + name);
  31. // turn off emission
  32. foreach (var system in systems)
  33. {
  34. var emission = system.emission;
  35. emission.enabled = false;
  36. }
  37. BroadcastMessage("Extinguish", SendMessageOptions.DontRequireReceiver);
  38. // wait for any remaining particles to expire
  39. yield return new WaitForSeconds(m_MaxLifetime);
  40. Destroy(gameObject);
  41. }
  42. public void Stop()
  43. {
  44. // stops the particle system early
  45. m_EarlyStop = true;
  46. }
  47. }
  48. }