Last active
June 27, 2020 00:24
-
-
Save Manamongods/639f1f73440d4105fdede9be822b7e49 to your computer and use it in GitHub Desktop.
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
//Steffen Vetne made this | |
//Creative Commons 0 | |
#if UNITY_EDITOR | |
using UnityEngine; | |
using UnityEditor; | |
[ExecuteInEditMode] | |
[RequireComponent(typeof(ParticleSystem))] | |
public class EditorParticles : MonoBehaviour | |
{ | |
private float previousTime; | |
private bool previousSelected; | |
private int playAfterFrames; | |
private void OnEnable() | |
{ | |
Play(); | |
previousTime = Time.realtimeSinceStartup; | |
EditorApplication.update -= EditorUpdate; | |
if (!Application.isPlaying) | |
EditorApplication.update += EditorUpdate; | |
else | |
Destroy(this); | |
} | |
private void OnDestroy() | |
{ | |
OnDisable(); | |
} | |
private void OnDisable() | |
{ | |
EditorApplication.update -= EditorUpdate; | |
} | |
private void Play() | |
{ | |
var ps = GetComponent<ParticleSystem>(); | |
ps.Stop(true, ParticleSystemStopBehavior.StopEmitting); | |
ps.Play(true); | |
} | |
private void EditorUpdate() | |
{ | |
if (this == null) | |
{ | |
EditorApplication.update -= EditorUpdate; | |
return; | |
} | |
if (Application.isPlaying) | |
{ | |
enabled = false; | |
return; | |
} | |
float time = Time.realtimeSinceStartup; | |
bool selected = Selection.Contains(gameObject.GetInstanceID()); | |
if (!selected) | |
{ | |
var ps = GetComponent<ParticleSystem>(); | |
float deltaTime = Mathf.Min(0.1f, time - previousTime); //I do this because UnityEditor.EditorApplication.update can happen multiple times in a single frame | |
if (deltaTime != 0) | |
ps.Simulate(deltaTime, true, false); | |
} | |
playAfterFrames--; | |
if (playAfterFrames == 0) | |
{ | |
Play(); | |
} | |
if (selected && !previousSelected) | |
playAfterFrames = 2; //These frames are used because it seems that the ParticleSystem's prewarm is not used on when auto-started in editor when selected. Only when pressing Restart | |
previousSelected = selected; | |
previousTime = time; | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment