You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.7 KiB

  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.startLifetime, 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. system.enableEmission = false;
  35. }
  36. BroadcastMessage("Extinguish", SendMessageOptions.DontRequireReceiver);
  37. // wait for any remaining particles to expire
  38. yield return new WaitForSeconds(m_MaxLifetime);
  39. Destroy(gameObject);
  40. }
  41. public void Stop()
  42. {
  43. // stops the particle system early
  44. m_EarlyStop = true;
  45. }
  46. }
  47. }