Skip to content

Instantly share code, notes, and snippets.

@Donnotron666
Created October 19, 2018 18:37
Show Gist options
  • Save Donnotron666/00d1293c583e11c4b1852683618f1761 to your computer and use it in GitHub Desktop.
Save Donnotron666/00d1293c583e11c4b1852683618f1761 to your computer and use it in GitHub Desktop.
Softly killing particle systems
using Client.Game.Utils;
using System;
using UnityEngine;
namespace Client.Game.Abilities.Utils
{
public class EffectTTL : MonoBehaviour
{
public EffectTTL ()
{
}
public float TimeToLive = 0;
public Action OnExpired;
void Update() {
TimeToLive -= Time.deltaTime;
if(TimeToLive <= 0) {
GameObject.Destroy(this.gameObject);
if(OnExpired != null)
OnExpired();
}
}
public static void Apply(GameObject go, float ttl) {
go.AddComponent<EffectTTL>().TimeToLive = ttl;
}
public static void SoftKillParticles(GameObject go, float ttl = 3f) {
foreach( var ps in go.GetComponentsInChildren<ParticleSystem>()) {
var pos = ps.transform.position;
ps.transform.SetParent(null, true);
ps.transform.position = pos;
ps.Stop();
if(ps.GetComponent<EffectTTL>() == null) {
Apply(ps.gameObject, ttl);
}
}
}
}
public class AudioFadeTTL : MonoBehaviour
{
public AudioFadeTTL()
{
}
public float TimeToLive;
public float LifeTime;
public float StartingVolume;
public AudioSource Source;
public float NormalizedTime()
{
return Mathf.Clamp01(TimeToLive / LifeTime);
}
void Update()
{
TimeToLive -= Time.unscaledDeltaTime;
Source.volume = NormalizedTime() * StartingVolume;
if (TimeToLive <= 0)
{
GameObject.Destroy(this.gameObject);
}
}
public static void Apply(AudioSource src, float ttl)
{
var comp = src.gameObject.AddComponent<AudioFadeTTL>();
comp.Source = src;
comp.StartingVolume = src.volume;
comp.TimeToLive = comp.LifeTime = ttl;
}
}
}
@Donnotron666
Copy link
Author

This exists so that game objects that have particle systems can be destroyed and their particles can be briefly re-parented to a temporary game object so they can be allowed to play out.

Usage would be something like:
EffectTTL.SoftKillParticles(projectile);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment