OwnButton.cs 2.08 KB
Newer Older
radow's avatar
radow committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using TMPro;

public class OwnButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler
{
    bool selected;
    bool isHovering;
    bool dirty, doAudio;

    AudioSource auds;
    Image buttonImage;
    TextColorSwap textSwap;
    Outline outline;
    TextMeshProUGUI text;

    public Color highlightColor, regularColor;
    public bool swapSprites;
    public Sprite highlightsprite, regularSprite;

    private void Start()
    {
        auds = GetComponent<AudioSource>();
        buttonImage= GetComponent<Image>();
        textSwap = GetComponentInChildren<TextColorSwap>();
        outline = GetComponent<Outline>();
        text = GetComponentInChildren<TextMeshProUGUI>();
    }


    public void OnDeselect(BaseEventData eventData)
    {
        if (selected) dirty = true;
        selected = false;
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        if (!isHovering) dirty = true;
        isHovering = true;
        doAudio = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        if (isHovering) dirty = true;
        isHovering = false;
    }

    public void OnSelect(BaseEventData eventData)
    {
        if (!selected) dirty = true;
        selected = true;
        doAudio = true;
    }

    private void Update()
    {
        if (dirty)
        {
            outline.enabled = selected||isHovering;
            outline.effectDistance = selected ? new Vector2(4,-4) : new Vector2(2,-2);
            buttonImage.color = (isHovering||selected) ? highlightColor : regularColor;
            text.fontStyle = isHovering ? FontStyles.Bold : FontStyles.Normal;
            if (isHovering || selected) textSwap.Select();
            else textSwap.DeSelect();
            if (doAudio) auds.Play();
            if (swapSprites) buttonImage.sprite = (isHovering || selected) ? highlightsprite : regularSprite;
            dirty = false;
            doAudio = false;
        }
    }
}