ShowOnHover.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. namespace SoftMasking.Samples {
  4. [RequireComponent(typeof(RectTransform))]
  5. public class ShowOnHover : UIBehaviour, IPointerEnterHandler, IPointerExitHandler {
  6. public CanvasGroup targetGroup;
  7. public bool forcedVisible {
  8. get { return _forcedVisible; }
  9. set {
  10. if (_forcedVisible != value) {
  11. _forcedVisible = value;
  12. UpdateVisibility();
  13. }
  14. }
  15. }
  16. bool _forcedVisible;
  17. bool _isPointerOver;
  18. protected override void Start() {
  19. base.Start();
  20. UpdateVisibility();
  21. }
  22. void UpdateVisibility() {
  23. SetVisible(ShouldBeVisible());
  24. }
  25. bool ShouldBeVisible() {
  26. return _forcedVisible || _isPointerOver;
  27. }
  28. void SetVisible(bool visible) {
  29. if (targetGroup)
  30. targetGroup.alpha = visible ? 1f : 0f;
  31. }
  32. public void OnPointerEnter(PointerEventData eventData) {
  33. _isPointerOver = true;
  34. UpdateVisibility();
  35. }
  36. public void OnPointerExit(PointerEventData eventData) {
  37. _isPointerOver = false;
  38. UpdateVisibility();
  39. }
  40. }
  41. }