Skip to content

Instantly share code, notes, and snippets.

@Anthelmed
Last active April 28, 2023 13:22
Show Gist options
  • Save Anthelmed/8362760b4a4acf6826cff176c865e8a1 to your computer and use it in GitHub Desktop.
Save Anthelmed/8362760b4a4acf6826cff176c865e8a1 to your computer and use it in GitHub Desktop.
A simple utils for fading in and out VisualElements. Code is under the MIT license: https://github.com/git/git-scm.com/blob/main/MIT-LICENSE.txt
using System;
using UnityEngine.UIElements;
using UnityEngine.UIElements.Experimental;
public static class UIAnimationsUtils
{
public static ValueAnimation<float> FadeIn(VisualElement visualElement, int durationMS, Func<float, float> easing, Action callback = null, bool disabledWhenInvisible = true)
{
var fromOpacity = visualElement.style.opacity.value;
return visualElement.experimental.animation.Start(fromOpacity, 1, durationMS, (_, opacity) =>
{
visualElement.style.opacity = opacity;
if (disabledWhenInvisible)
visualElement.style.display = opacity > 0 ? DisplayStyle.Flex : DisplayStyle.None;
})
.OnCompleted(callback)
.Ease(easing);
}
public static ValueAnimation<float> FadeOut(VisualElement visualElement, int durationMS, Func<float, float> easing, Action callback = null, bool disabledWhenInvisible = true)
{
var fromOpacity = visualElement.style.opacity.value;
return visualElement.experimental.animation.Start(fromOpacity, 0, durationMS, (_, opacity) =>
{
visualElement.style.opacity = opacity;
if (disabledWhenInvisible)
visualElement.style.display = opacity > 0 ? DisplayStyle.Flex : DisplayStyle.None;
})
.OnCompleted(callback)
.Ease(easing);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment