Last active
February 17, 2021 10:22
-
-
Save FlaShG/5f1ddfab726eb5f3f06342068d3165cf to your computer and use it in GitHub Desktop.
A superclass for classes that manipulate particles in Update.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| /// <summary> | |
| /// Create a subclass of this class to manipulate particles in Update any way you see fit. | |
| /// </summary> | |
| [RequireComponent(typeof(ParticleSystem))] | |
| [ExecuteInEditMode] | |
| public abstract class ParticleManipulator : MonoBehaviour | |
| { | |
| new protected ParticleSystem particleSystem { get; private set; } | |
| protected ParticleSystem.Particle[] particles { get; private set; } | |
| private void Awake() | |
| { | |
| particleSystem = GetComponent<ParticleSystem>(); | |
| UpdateMaxParticles(); | |
| } | |
| private void Update() | |
| { | |
| if (!IsAvailable()) return; | |
| #if UNITY_EDITOR | |
| if (!particleSystem) | |
| { | |
| Awake(); | |
| } | |
| #endif | |
| var size = particleSystem.GetParticles(particles); | |
| for (var i = 0; i < size; i++) | |
| { | |
| UpdateParticle(i); | |
| } | |
| particleSystem.SetParticles(particles); | |
| } | |
| /// <summary> | |
| /// Override this to define per-particle behaviour. | |
| /// Update particles[index] any way you see fit. | |
| /// Consider using particles.Length fpr some effects. | |
| /// </summary> | |
| protected abstract void UpdateParticle(int index); | |
| /// <summary> | |
| /// Override this to return false if for some reason, update should not happen. | |
| /// For example: If there are values missing in the subclass. | |
| /// </summary> | |
| protected virtual bool IsAvailable() | |
| { | |
| return true; | |
| } | |
| /// <summary> | |
| /// Call this after you happened to change "Max Particles" of the ParticleSystem. | |
| /// </summary> | |
| public void UpdateMaxParticles() | |
| { | |
| particles = new ParticleSystem.Particle[particleSystem.main.maxParticles]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment