| | 1 | | using System; |
| | 2 | | using System.Collections; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using UnityEngine; |
| | 5 | | using UnityEngine.EventSystems; |
| | 6 | | using UnityEngine.UI; |
| | 7 | |
|
| | 8 | | namespace DCL.Builder |
| | 9 | | { |
| | 10 | | public class ButtonColorChange : MonoBehaviour, |
| | 11 | | IPointerDownHandler, IPointerUpHandler, |
| | 12 | | IPointerEnterHandler, IPointerExitHandler |
| | 13 | | { |
| | 14 | | [SerializeField] internal Image buttonImage; |
| | 15 | | [SerializeField] internal Color onIdleColor; |
| | 16 | | [SerializeField] internal Color onHoverColor; |
| | 17 | | [SerializeField] internal Color onPressedColor; |
| | 18 | | [SerializeField] internal Color onDisabledColor; |
| | 19 | |
|
| | 20 | | private bool isHovered; |
| | 21 | | private bool isPressed; |
| | 22 | |
|
| | 23 | | public enum State |
| | 24 | | { |
| | 25 | | IDLE = 0, |
| | 26 | | HOVER = 1, |
| | 27 | | PRESSED = 2, |
| | 28 | | DISABLED = 3 |
| | 29 | | } |
| | 30 | |
|
| | 31 | | private State state = State.IDLE; |
| | 32 | |
|
| | 33 | | private void SetColor(State currentState) |
| | 34 | | { |
| 0 | 35 | | Color colorToUse = onIdleColor; |
| | 36 | | switch (currentState) |
| | 37 | | { |
| | 38 | | case State.HOVER: |
| 0 | 39 | | colorToUse = onHoverColor; |
| 0 | 40 | | break; |
| | 41 | | case State.PRESSED: |
| 0 | 42 | | colorToUse = onPressedColor; |
| 0 | 43 | | break; |
| | 44 | | case State.DISABLED: |
| 0 | 45 | | colorToUse = onDisabledColor; |
| | 46 | | break; |
| | 47 | |
|
| | 48 | | } |
| 0 | 49 | | buttonImage.color = colorToUse; |
| 0 | 50 | | } |
| | 51 | |
|
| | 52 | | private void SetState(State state) |
| | 53 | | { |
| 0 | 54 | | this.state = state; |
| 0 | 55 | | SetColor(state); |
| 0 | 56 | | } |
| | 57 | |
|
| | 58 | | public void OnPointerDown(PointerEventData eventData) |
| | 59 | | { |
| 0 | 60 | | isPressed = true; |
| 0 | 61 | | SetState(State.PRESSED); |
| 0 | 62 | | } |
| | 63 | |
|
| | 64 | | public void OnPointerUp(PointerEventData eventData) |
| | 65 | | { |
| 0 | 66 | | isPressed = false; |
| 0 | 67 | | if(!isHovered) |
| 0 | 68 | | SetState(State.IDLE); |
| | 69 | | else |
| 0 | 70 | | SetState(State.HOVER); |
| 0 | 71 | | } |
| | 72 | |
|
| | 73 | | public void OnPointerEnter(PointerEventData eventData) |
| | 74 | | { |
| 0 | 75 | | isHovered = true; |
| 0 | 76 | | SetState(State.HOVER); |
| 0 | 77 | | } |
| | 78 | |
|
| | 79 | | public void OnPointerExit(PointerEventData eventData) |
| | 80 | | { |
| 0 | 81 | | isHovered = false; |
| 0 | 82 | | if(!isPressed) |
| 0 | 83 | | SetState(State.IDLE); |
| | 84 | | else |
| 0 | 85 | | SetState(State.PRESSED); |
| 0 | 86 | | } |
| | 87 | | } |
| | 88 | | } |