我有一个 UI 按钮。我想在用户按下按钮时显示文本,并在用户释放按钮时隐藏文本。
我怎样才能做到这一点?
这个 anwser基本上没问题,但有一个很大的缺点:你不能在 Inspector 中有额外的字段,因为Button已经有一个内置的 EditorScript 会覆盖默认的 Inspector。
相反,我会将其实现为实现IPointerDownHandler和IPointerUpHandler的完全附加组件(并且也许IPointerExitHandler在按住鼠标/指针仍然按下时退出按钮时也会重置)。
为了在按钮保持按下状态时做某事,我会使用Coroutine。
一般来说,我会使用UnityEvents:
[RequireComponent(typeof(Button))]
public class PointerDownUpHandler : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
{
public UnityEvent onPointerDown;
public UnityEvent onPointerUp;
// gets invoked every frame while pointer is down
public UnityEvent whilePointerPressed;
private Button _button;
private void Awake()
{
_button = GetComponent<Button>();
}
private IEnumerator WhilePressed()
{
// this looks strange but is okey in a Coroutine
// as long as you yield somewhere
while(true)
{
whilePointerPressed?.Invoke();
yield return null;
}
}
public void OnPointerDown(PointerEventData eventData)
{
// ignore if button not interactable
if(!_button.interactable) return;
// just to be sure kill all current routines
// (although there should be none)
StopAllCoroutines();
StartCoroutine(WhilePressed);
onPointerDown?.Invoke();
}
public void OnPointerUp(PointerEventData eventData)
{
StopAllCoroutines();
onPointerUp?.Invoke();
}
public void OnPointerExit(PointerEventData eventData)
{
StopAllCoroutines();
onPointerUp?.Invoke();
}
// Afaik needed so Pointer exit works .. doing nothing further
public void OnPointerEnter(PointerEventData eventData) { }
}
您可以引用 中的任何回调onPointerDown,onPointerUp并且whilePointerPressed就像onClick使用Button.
您必须通过扩展 Button 类并覆盖 OnPoiterDown 和 OnPointerUp 方法来创建自己的自定义按钮。将 MyButton 组件而不是 Button 附加到您的游戏对象
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MyButton : Button
{
public override void OnPointerDown(PointerEventData eventData)
{
base.OnPointerDown(eventData);
Debug.Log("Down");
//show text
}
public override void OnPointerUp(PointerEventData eventData)
{
base.OnPointerUp(eventData);
Debug.Log("Up");
//hide text
}
}