1 user-interface button unity-game-engine
我有一个用户界面按钮。我想在用户按下按钮时显示文本,并在用户释放按钮时隐藏文本。
我怎样才能做到这一点?
这个 anwser基本上没问题,但有一个巨大的缺点:您不能在检查器中添加其他字段,因为Button已经有一个内置的 EditorScript 会覆盖默认的检查器 - 您每次都需要通过自定义检查器来扩展它。
相反,我会将其实现为完全附加的组件,实现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) { }
}
Run Code Online (Sandbox Code Playgroud)
您可以引用 中的任何回调onPointerDown,onPointerUp就像whilePointerPressed处理onClick的事件一样Button。
| 归档时间: |
|
| 查看次数: |
20972 次 |
| 最近记录: |