在需要监听 OnClick 事件的对象上添加 PressableButton、BoxCollider 组件。如果是UGUI,还需要添加 UGUIInputAdapter 组件(响应鼠标、键盘操作)。
PressableButton 继承 StatefulInteractable,且实现了 IXRProximityInteractable 接口方法。
OnClick 事件逻辑由 StatefulInteractable 类实现。
namespace MixedReality.Toolkit
{
[AddComponentMenu("MRTK/Core/Stateful Interactable")]
public class StatefulInteractable : MRTKBaseInteractable
{
/// <summary>
/// Fired when the interactable is fully clicked (select + deselect)
/// </summary>
[field: SerializeField, FormerlySerializedAs("onClicked"), Tooltip("Fired when the interactable is fully clicked")]
public UnityEvent OnClicked { get; private set; } = new UnityEvent();
protected virtual void OnFirstSelectEntered(SelectEnterEventArgs args)
{
using (OnFirstSelectEnteredPerfMarker.Auto())
{
if (CanClickOnFirstSelectEntered(args))
{
TryToggle();
OnClicked.Invoke();
}
}
}
protected virtual void OnLastSelectExited(SelectExitEventArgs args)
{
using (OnLastSelectExitedPerfMarker.Auto())
{
if (CanClickOnLastSelectExited(args))
{
TryToggle();
OnClicked.Invoke();
}
}
}
}
}