有没有办法在没有OnClick函数的情况下触发事件?我想制作一款 Cardboard VR 游戏,玩家只需在特定时间内注视某个地点即可传送到某个位置。就像玩家会看一个圆圈3秒,它会将玩家传送到该圆圈中。
我还没有尝试过任何东西,因为我是 Unity 新手...
当然可以。我不知道 Cardboard VR 的具体工作原理,但例如使用 HoloLens (1),您始终拥有此头部指针。
IPointerEnterHandler
/IPointerExitHandler
并做类似的事情
public void TimedTrigger : MonoBehaviour, IPonterEnterHandler, IPointerExitHandler
{
public float duration = 2f;
public UnityEvent onCompleted;
public UnityEvent<float> onProgress;
private Coroutine routine;
public void OnPointerEnter(PointerEventData pointerEventData)
{
routine = StartCoroutine(Routine());
}
public void OnPointerExit(PointerEventData pointerEventData)
{
if(routine != null) StopCoroutine(routine);
}
private IEnumerator Routine()
{
for(var time = 0f; time < duration; time += Time.deltaTime)
{
var progress = Mathf.Clamp01(time / duration);
onProgress.Invoke(progress);
yield return null;
}
routine = null;
onProgress.Invoke(1f);
onCompleted.Invoke();
}
}
这将向检查器公开两个事件(类似于
Button.onClick
),您可以将方法连接到
OnCompleted
- 非常不言自明 - 在对象聚焦 duration
秒后称为once
OnProgress
- 也是不言自明的 - 在对焦过程中称为 每帧。通过的float
显示从0
到1
的进度
可以使用,例如向用户展示一些视觉反馈(例如,我们过去使用的头部指针周围有圆形填充的图像)