Last active
August 16, 2022 22:17
-
-
Save R3tr0BoiDX/1607500b036531e17dadaa7e6255818d to your computer and use it in GitHub Desktop.
Editor integration for SimpleAnimator
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
#if UNITY_EDITOR | |
using UnityEditor; | |
using UnityEngine; | |
using UnityEngine.UI; | |
namespace Tools { | |
[CustomEditor(typeof(SimpleAnimator))] //find here: https://gist.github.com/R3tr0BoiDX/d84e91a03d020f2169d92446f1ffb857 | |
public sealed class SimpleAnimatorEditor : Editor { | |
private SimpleAnimator anim; | |
private bool animate; | |
private Sprite baseSprite; | |
private int currentSpriteIndex; | |
private bool delay; | |
private Image image; | |
private float lastEditorUpdate; | |
private float localTime; | |
private SpriteRenderer rend; | |
private float resetDelay; | |
private void OnEnable() { | |
EditorApplication.update += OnEditorUpdate; | |
} | |
private void OnDisable() { | |
EditorApplication.update -= OnEditorUpdate; | |
} | |
public override void OnInspectorGUI() { | |
base.OnInspectorGUI(); | |
anim = (SimpleAnimator)target; | |
if (anim.UseGUIMode) { | |
image = ((MonoBehaviour)target).gameObject.GetComponent<Image>(); | |
} else { | |
rend = ((MonoBehaviour)target).gameObject.GetComponent<SpriteRenderer>(); | |
} | |
Rect rect = EditorGUILayout.GetControlRect(false, 1); | |
EditorGUI.DrawRect(rect, Color.grey); | |
GUIContent content = new("Reset Delay", "Time until the animation resets"); | |
resetDelay = EditorGUILayout.FloatField(content, resetDelay, EditorStyles.numberField); | |
if (GUILayout.Button("Animate")) { | |
baseSprite = anim.UseGUIMode ? image.sprite : rend.sprite; | |
animate = true; | |
} | |
} | |
private void OnEditorUpdate() { | |
float deltaTime = Time.realtimeSinceStartup - lastEditorUpdate; | |
localTime += deltaTime; | |
if (animate && localTime > anim.TimeBetweenFrames) { | |
localTime = 0; | |
SetSprite(anim.Frames[currentSpriteIndex]); | |
currentSpriteIndex++; | |
if (currentSpriteIndex >= anim.Frames.Length) { | |
currentSpriteIndex = 0; | |
delay = true; | |
animate = false; | |
} | |
} else if (delay) { | |
if (localTime > resetDelay) { | |
SetSprite(baseSprite); | |
delay = false; | |
} | |
} | |
lastEditorUpdate = Time.realtimeSinceStartup; | |
} | |
private void SetSprite(Sprite _sprite) { | |
if (anim.UseGUIMode) { | |
image.sprite = _sprite; | |
} else { | |
rend.sprite = _sprite; | |
} | |
} | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment