Unity编辑器 - 编辑器控制特效播放

时间:2022-09-25 16:28:55

编辑器控制特效播放

Unity的动画编辑器不能预览粒子系统的播放,为了方便预览特效,设想制作一个预览特效的工具,通常一个特效有三种组件:

- Animation

- Animator

- ParticleSystem

其中Unity编辑器在编辑器模式下会控制粒子的播放,所以这里控制特效播放的功能只能在播放模式下使用。

代码

using UnityEngine;
using UnityEditor;
using System; public class EffctPlayBackWin : EditorWindow {
[MenuItem("Tools/EffctPlayBack")]
static void DoIt() {
GetWindow<EffctPlayBackWin>();
} private Transform _root;
private ParticleSystem[] _particles;
private Animation[] _animations;
private Animator[] _animators;
private float _time;
private int frameCount = 5 * 60 + 1; private Rect _rect = new Rect(5, 5, 300, 600); private void OnGUI() {
EditorGUIUtility.labelWidth = 60f;
GUILayout.BeginArea(_rect);
{
//get those components from root transform
EditorGUI.BeginChangeCheck();
_root = EditorGUILayout.ObjectField("root:", _root, typeof(Transform), true) as Transform;
if (EditorGUI.EndChangeCheck()) {
FindComponets();
} //use slider to control Animation,Animator and a ParticleSystem playback
EditorGUI.BeginChangeCheck();
_time = EditorGUILayout.Slider("Time:", _time, 0, 5);
if (EditorGUI.EndChangeCheck()) {
PlayBackAnimation();
PlayBackAnimator();
PlayBackParticle();
} GUILayout.Space(10);
}
GUILayout.EndArea();
EditorGUIUtility.labelWidth = 0f;
} private void PlayBackParticle() {
if (_particles != null) {
foreach (var psys in _particles) {
//need to close the random seed to control ParticleSystem playback
psys.useAutoRandomSeed = false;
// Simulate the ParticleSystem to the time
psys.Simulate(_time);
}
}
} private void PlayBackAnimation() {
if (_animations != null) {
foreach (var animation in _animations) {
if (animation.clip) {
var state = animation[animation.clip.name];
if (state) {
animation.Play(state.name);
state.time = _time;
state.speed = 0f;
}
}
}
}
} private void PlayBackAnimator() {
if (_animators == null)
return;
foreach (var at in _animators) {
at.playbackTime = _time;
at.Update(0);
}
} private void FindComponets() {
if (_root) {
_animations = _root.GetComponentsInChildren<Animation>();
_animators = _root.GetComponentsInChildren<Animator>();
_particles = _root.GetComponentsInChildren<ParticleSystem>(); //Bake Animator's animation to the buffer
if (_animators != null) {
foreach (var at in _animators) {
at.Rebind();
at.StopPlayback();
at.recorderStartTime = 0f;
at.StartRecording(frameCount);//will the recorded frames
for (int i = 1; i <= frameCount; i++) {
//recording every frame with delta time
at.Update(1.0f / 60);
}
//stop record and start playback
at.StopRecording();
at.StartPlayback();
at.playbackTime = 0f;
at.Update(0);
}
}
}
}
}

Unity编辑器 - 编辑器控制特效播放