2025-10-03 00:02:43 -04:00
using UnityEngine ;
namespace MoreMountains.Tools
{
/// <summary>
2026-03-20 11:56:50 -04:00
/// Add this class to a ParticleSystem so it auto destroys once it has stopped emitting.
/// Make sure your ParticleSystem isn't looping, otherwise this script will be useless
2025-10-03 00:02:43 -04:00
/// </summary>
[AddComponentMenu("More Mountains/Tools/Particles/MM Auto Destroy Particle System")]
2026-03-20 11:56:50 -04:00
public class MMAutoDestroyParticleSystem : MonoBehaviour
{
/// True if the ParticleSystem should also destroy its parent
public bool DestroyParent ;
2025-10-03 00:02:43 -04:00
2026-03-20 11:56:50 -04:00
/// If for some reason your particles don't get destroyed automatically at the end of the emission, you can force a destroy after a delay. Leave it at zero otherwise.
public float DestroyDelay ;
2025-10-03 00:02:43 -04:00
2026-03-20 11:56:50 -04:00
protected ParticleSystem _particleSystem ;
protected bool _started ;
protected float _startTime ;
2025-10-03 00:02:43 -04:00
2026-03-20 11:56:50 -04:00
/// <summary>
/// Initialization, we get the ParticleSystem component
/// </summary>
protected virtual void Start ( )
{
_started = false ;
_particleSystem = GetComponent < ParticleSystem > ( ) ;
if ( DestroyDelay ! = 0 ) _startTime = Time . time ;
}
2025-10-03 00:02:43 -04:00
2026-03-20 11:56:50 -04:00
/// <summary>
/// When the ParticleSystem stops playing, we destroy it.
/// </summary>
protected virtual void Update ( )
{
if ( DestroyDelay ! = 0 & & Time . time - _startTime > DestroyDelay ) DestroyParticleSystem ( ) ;
if ( _particleSystem . isPlaying )
{
_started = true ;
return ;
}
DestroyParticleSystem ( ) ;
}
/// <summary>
/// Destroys the particle system.
/// </summary>
protected virtual void DestroyParticleSystem ( )
{
if ( ! _started ) return ;
if ( transform . parent ! = null )
if ( DestroyParent )
Destroy ( transform . parent . gameObject ) ;
Destroy ( gameObject ) ;
}
}
2025-10-03 00:02:43 -04:00
}