This pattern was created when we attempted to make an effect that was like a fireball, where one script controlled the movement and a ParticleEmitter created the smoke-trail effect. The problem we were setting was that the particle trail would just blink out of existence. A real fireball's trail would disapate after the fireball was destroyed. Another much bigger problem is that the smoke trail would instantly appear when the fireball was respawned later (we wanted the smoke to emit fresh, and it was, but the old smoke hadn't died yet, it was just deactivated) We fixed this by making the trail a seperate prefab, which is pooled as well. When the fireball is spawned, it automatically spawns a trail for itself, uses a UnityConstraint TransformConstraint to make it follow along as it flies through the air, and PoolManager's automatic ParticleEmitter functionality despawns the trail instance once its emitter is shut off and all particles die. Here is the pattern used... (This code has not been tested. Please report any issues found) public class Fireball : MonoBehaviour { public ParticleEmitter trailPrefab; // Cache private ParticleEmitter trail private TransformConstraint trailCns; private void Awake() { this.xform = this.transform; } private void OnSpawned() { // Spawn the a trail instance for this fireball // Note: this.trailPrefab is a ParticleEmitter, not a Transform. this.trail = PoolManager.Pools["Effects"].Spawn(this.trailPrefab, this.xform.position, this.xform.rotation); // Make it follow this transform without the need to reparent. // TransformConstraint requires UnityConstraints this.trailCns = this.trail.GetComponent<TransformConstraint>(); this.trailCns.target = this.xform; } private void OnDespawned() { // Stop emitting particles. // The trail will die when all particles are dead because of // Spawn(ParticleEmitter) in OnSpawned. this.trail.emit = false; // Remove the trails reference to this object so it doesn't follow // once despawned. Be sure to set the constraint's "No Target mode" // to "DoNothing" this.trailCns.target = null; // Clean up reference just for safty this.trailCns = null; this.trail = null; } } |
Example Patterns >