Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A superclass for classes that manipulate particles in Update.
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, size);
}
particleSystem.SetParticles(particles, size);
}
/// <summary>
/// Override this to define per-particle behaviour.
/// Update particles[index] any way you see fit.
/// </summary>
protected abstract void UpdateParticle(int index, int size);
/// <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
You can’t perform that action at this time.