UIImageButton.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. using System;
  2. using UnityEngine;
  3. [AddComponentMenu("NGUI/UI/Image Button")]
  4. public class UIImageButton : MonoBehaviour
  5. {
  6. public bool isEnabled
  7. {
  8. get
  9. {
  10. Collider component = base.gameObject.GetComponent<Collider>();
  11. return component && component.enabled;
  12. }
  13. set
  14. {
  15. Collider component = base.gameObject.GetComponent<Collider>();
  16. if (!component)
  17. {
  18. return;
  19. }
  20. if (component.enabled != value)
  21. {
  22. component.enabled = value;
  23. this.UpdateImage();
  24. }
  25. }
  26. }
  27. private void OnEnable()
  28. {
  29. if (this.target == null)
  30. {
  31. this.target = base.GetComponentInChildren<UISprite>();
  32. }
  33. this.UpdateImage();
  34. }
  35. private void OnValidate()
  36. {
  37. if (this.target != null)
  38. {
  39. if (string.IsNullOrEmpty(this.normalSprite))
  40. {
  41. this.normalSprite = this.target.spriteName;
  42. }
  43. if (string.IsNullOrEmpty(this.hoverSprite))
  44. {
  45. this.hoverSprite = this.target.spriteName;
  46. }
  47. if (string.IsNullOrEmpty(this.pressedSprite))
  48. {
  49. this.pressedSprite = this.target.spriteName;
  50. }
  51. if (string.IsNullOrEmpty(this.disabledSprite))
  52. {
  53. this.disabledSprite = this.target.spriteName;
  54. }
  55. }
  56. }
  57. private void UpdateImage()
  58. {
  59. if (this.target != null)
  60. {
  61. if (this.isEnabled)
  62. {
  63. this.SetSprite((!UICamera.IsHighlighted(base.gameObject)) ? this.normalSprite : this.hoverSprite);
  64. }
  65. else
  66. {
  67. this.SetSprite(this.disabledSprite);
  68. }
  69. }
  70. }
  71. private void OnHover(bool isOver)
  72. {
  73. if (this.isEnabled && this.target != null)
  74. {
  75. this.SetSprite((!isOver) ? this.normalSprite : this.hoverSprite);
  76. }
  77. }
  78. private void OnPress(bool pressed)
  79. {
  80. if (pressed)
  81. {
  82. this.SetSprite(this.pressedSprite);
  83. }
  84. else
  85. {
  86. this.UpdateImage();
  87. }
  88. }
  89. private void SetSprite(string sprite)
  90. {
  91. if (this.target.atlas == null || this.target.atlas.GetSprite(sprite) == null)
  92. {
  93. return;
  94. }
  95. this.target.spriteName = sprite;
  96. if (this.pixelSnap)
  97. {
  98. this.target.MakePixelPerfect();
  99. }
  100. }
  101. public UISprite target;
  102. public string normalSprite;
  103. public string hoverSprite;
  104. public string pressedSprite;
  105. public string disabledSprite;
  106. public bool pixelSnap = true;
  107. }