Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using UnityEngine;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;// Required when using Event data.
- public class AnimatedButtonScaleDownOnPress : MonoBehaviour, IPointerUpHandler,IPointerDownHandler,IPointerEnterHandler,IPointerExitHandler {
- [SerializeField]
- Vector3 scaleDownSize = new Vector3 (0.9f,0.9f,1f); // The size when the button is pressed
- private Vector3 defaultScale; // This is the original size of the button
- [Space]
- [SerializeField]
- bool doColorTintOnPress = true; // default - tint the button on press
- [SerializeField]
- Color colorTint = new Color (0.7f, 0.7f, 0.7f, 1); // slight grey
- Color colorOriginal; // the original color of the button before pressed
- Image imageOfButton;
- private bool pressedButton;
- private bool movedPointerOffButtonAfterPress; // Keep track of button pressed but moved pointer away from button but held the pressed input
- // Use this for initialization
- void Start () {
- // Get the image component
- imageOfButton = GetComponent<Image> ();
- // Save the original button color
- colorOriginal = imageOfButton.color;
- // Save the original tranform scale
- defaultScale = transform.localScale;
- }
- #region Pointer Events
- public void OnPointerDown(PointerEventData eventData)
- {
- PressAnimation ();
- }
- public void OnPointerUp(PointerEventData eventData)
- {
- ResetAnimation ();
- // Button is no longer pressed - reset the bools
- movedPointerOffButtonAfterPress = false;
- pressedButton = false;
- }
- public void OnPointerEnter(PointerEventData eventData)
- {
- // Check if pressed the button, moved the pointer off the button but held the input
- // then moved back onto the button (redo the press animation)
- if (pressedButton == true && movedPointerOffButtonAfterPress == true)
- {
- PressAnimation ();
- }
- }
- public void OnPointerExit(PointerEventData eventData)
- {
- ResetAnimation ();
- movedPointerOffButtonAfterPress = true;
- }
- #endregion
- #region Button Animations
- public void PressAnimation()
- {
- // Set the button as pressed;
- pressedButton = true;
- // Change the color if needed
- if (doColorTintOnPress == true){
- imageOfButton.color = colorTint;
- }
- // Update the scale
- transform.localScale = scaleDownSize;
- }
- public void ResetAnimation()
- {
- // Reset the scale
- transform.localScale = defaultScale;
- // Reset the color
- if (doColorTintOnPress == true){
- imageOfButton.color = colorOriginal;
- }
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment