| | 1 | | using DG.Tweening; |
| | 2 | | using UnityEngine; |
| | 3 | |
|
| | 4 | | public class ShowHideAnimator : MonoBehaviour |
| | 5 | | { |
| | 6 | | private const float BASE_DURATION = 0.2f; |
| | 7 | |
|
| | 8 | | public event System.Action<ShowHideAnimator> OnWillFinishHide; |
| | 9 | | public event System.Action<ShowHideAnimator> OnWillFinishStart; |
| | 10 | |
|
| 17591 | 11 | | public bool hideOnEnable = true; |
| 17591 | 12 | | public float animSpeedFactor = 1.0f; |
| | 13 | | public bool disableAfterFadeOut; |
| | 14 | |
|
| | 15 | | [SerializeField] private CanvasGroup canvasGroup; |
| | 16 | |
|
| | 17 | | private int? visibleParamHashValue = null; |
| | 18 | |
|
| 53 | 19 | | public bool isVisible => canvasGroup == null || canvasGroup.blocksRaycasts; |
| | 20 | |
|
| | 21 | | private void Awake() |
| | 22 | | { |
| 11725 | 23 | | if (TryGetComponent(out Animator animator)) //Remove old behaviour |
| 11563 | 24 | | Destroy(animator); |
| | 25 | |
|
| 11725 | 26 | | if (canvasGroup == null) |
| 6486 | 27 | | canvasGroup = GetComponent<CanvasGroup>(); |
| 11725 | 28 | | } |
| | 29 | |
|
| | 30 | | private void OnEnable() |
| | 31 | | { |
| 17609 | 32 | | if (hideOnEnable) |
| | 33 | | { |
| 618 | 34 | | Hide(true); |
| | 35 | | } |
| 17609 | 36 | | } |
| | 37 | |
|
| | 38 | | public void Show(bool instant = false) |
| | 39 | | { |
| 172 | 40 | | canvasGroup.blocksRaycasts = true; |
| | 41 | |
|
| | 42 | | //When instant, we use duration 0 instead of just modifying the canvas group to mock the old animator behaviour |
| 172 | 43 | | var duration = instant ? 0 : BASE_DURATION * animSpeedFactor; |
| 172 | 44 | | canvasGroup.DOKill(); |
| 172 | 45 | | canvasGroup.DOFade(1, duration) |
| | 46 | | .SetEase(Ease.InOutQuad) |
| 8 | 47 | | .OnComplete(() => OnWillFinishStart?.Invoke(this)) |
| | 48 | | .SetLink(canvasGroup.gameObject, LinkBehaviour.KillOnDestroy) |
| | 49 | | .SetLink(canvasGroup.gameObject, LinkBehaviour.KillOnDisable); |
| 172 | 50 | | } |
| | 51 | |
|
| | 52 | | public void Hide(bool instant = false) |
| | 53 | | { |
| 1010 | 54 | | canvasGroup.blocksRaycasts = false; |
| | 55 | |
|
| | 56 | | //When instant, we use duration 0 instead of just modifying the canvas group to mock the old animator behaviour |
| 1010 | 57 | | var duration = instant ? 0 : BASE_DURATION * animSpeedFactor; |
| 1010 | 58 | | canvasGroup.DOKill(); |
| 1010 | 59 | | canvasGroup.DOFade(0, duration) |
| | 60 | | .SetEase(Ease.InOutQuad) |
| | 61 | | .OnComplete(() => |
| | 62 | | { |
| 92 | 63 | | OnWillFinishHide?.Invoke(this); |
| | 64 | |
|
| 92 | 65 | | if (disableAfterFadeOut && gameObject != null) |
| | 66 | | { |
| 59 | 67 | | gameObject.SetActive(false); |
| | 68 | | } |
| 92 | 69 | | }) |
| | 70 | | .SetLink(canvasGroup.gameObject, LinkBehaviour.KillOnDestroy) |
| | 71 | | .SetLink(canvasGroup.gameObject, LinkBehaviour.KillOnDisable); |
| 1010 | 72 | | } |
| | 73 | | } |