Skip to content

Instantly share code, notes, and snippets.

@noio
Created November 7, 2016 12:21
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 noio/b589f07721fd7a432216a2a1e1ae7ef5 to your computer and use it in GitHub Desktop.
Save noio/b589f07721fd7a432216a2a1e1ae7ef5 to your computer and use it in GitHub Desktop.
/* By Thomas "noio" van den Berg
Add this script to the UI.Buttons that form
a left/right arrow pair. For each button,
drag the *other* button into the "other" field.
It requires that your buttons are animated using
"Transition: Animation", (not Sprite Swap) with an
animator that has the default Trigger parameters defined
("Normal", "Highlighted", "Pressed")
*/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class HorizontalArrowKey : MonoBehaviour, ISelectHandler, IDeselectHandler, IPointerExitHandler
{
public enum Direction
{
Left,
Right
}
public Direction direction;
public HorizontalArrowKey other;
bool _selected;
Rewired.Player _rewired;
Animator _animator;
Button _button;
void Awake()
{
_button = Require.Component<Button>(this);
_rewired = Rewired.ReInput.players.GetPlayer(0);
_animator = Require.Component<Animator>(this);
}
void Update()
{
if (_selected || other._selected)
{
if (direction == Direction.Left && _rewired.GetNegativeButtonDown(RewiredAxis.Horizontal))
{
StartCoroutine(Press());
}
else if (direction == Direction.Right && _rewired.GetButtonDown(RewiredAxis.Horizontal))
{
StartCoroutine(Press());
}
}
}
IEnumerator Press()
{
_button.onClick.Invoke();
_animator.ResetTrigger("Normal");
_animator.ResetTrigger("Highlighted");
_animator.SetTrigger("Pressed");
float elapsed = 0;
while (elapsed < 0.1f)
{
elapsed += Time.unscaledDeltaTime;
yield return null;
}
_animator.SetTrigger("Highlighted");
}
public void OnSelect(BaseEventData eventData)
{
_selected = true;
// _animator.SetTrigger("Highlighted");
other._animator.ResetTrigger("Normal");
other._animator.SetTrigger("Highlighted");
}
public void OnDeselect(BaseEventData eventData)
{
_selected = false;
// _animator.SetTrigger("Normal");
other._animator.SetTrigger("Normal");
}
public void OnPointerExit(PointerEventData eventData)
{
if (other._selected)
{
_animator.ResetTrigger("Normal");
_animator.SetTrigger("Highlighted");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment