Skip to content

Instantly share code, notes, and snippets.

@BigHandInSky
Created January 13, 2021 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BigHandInSky/c55a457728654e96236313376683a5d6 to your computer and use it in GitHub Desktop.
Save BigHandInSky/c55a457728654e96236313376683a5d6 to your computer and use it in GitHub Desktop.
An example of how to react to UGUI EventSystem select states to get a reactive button
using System;
using _project.utilities;
using DG.Tweening;
using Sirenix.OdinInspector;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.UI.ProceduralImage;
namespace _project.ui
{
/// <summary>
/// Common driver for button animations
/// </summary>
public class ButtonFocusReactor : MonoBehaviour
{
private bool _isSelectedByEventSystem => EventSystem.current.currentSelectedGameObject == gameObject;
private bool _isConsideredSelected => _isSelectedByEventSystem || lockAsSelected;
private bool _lastSelectionState;
public bool canAnimate = true;
public float selectionTweenLength = 0.25f;
[ReadOnly]
public bool lockAsSelected; // if unfocused, keep set to the selected view
// https://assetstore.unity.com/packages/tools/gui/procedural-ui-image-52200
[Header("Outline")]
public ProceduralImage outlineGraphic;
[Space( 10 )]
public float selectedBorder = 48; // use an enormous stroke to do the fill, rather than go to 0 which "fades out"
public float unselectedBorder = 2;
[Header("Text")]
public TextMeshProUGUI text;
public Graphic icon; // optional
public Color onSelectedTextColour = Color.white;
public Color onUnselectedTextColour = Color.white;
public TMP_FontAsset onSelectedFont;
public TMP_FontAsset onUnselectedFont;
private void Reset()
{
outlineGraphic = GetComponentInChildren<ProceduralImage>();
text = GetComponentInChildren<TextMeshProUGUI>();
icon = GetComponentInChildren<Image>();
}
private void Update()
{
if ( _lastSelectionState != _isConsideredSelected && canAnimate )
{
_lastSelectionState = _isConsideredSelected;
DoChange( _lastSelectionState );
}
}
protected virtual void DoChange( bool isSelected )
{
outlineGraphic.DOKill( true );
outlineGraphic.DOBorderWidth(
isSelected ? selectedBorder : unselectedBorder,
selectionTweenLength );
text.DOKill( true );
text.DOColor(
isSelected
? onSelectedTextColour
: onUnselectedTextColour,
selectionTweenLength );
if ( onSelectedFont && onUnselectedFont )
text.font = isSelected ? onSelectedFont : onUnselectedFont;
if ( icon )
{
icon.DOKill( true );
icon.DOColor(
isSelected
? onSelectedTextColour
: onUnselectedTextColour,
selectionTweenLength );
}
}
protected virtual void OnDestroy()
{
outlineGraphic.DOKill();
text.DOKill();
if(icon)
icon.DOKill();
canAnimate = false;
Destroy( gameObject );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment