如何检测UI Image的悬停时长以实现悬停1秒后放大的效果
解决方案
不用单独实现鼠标悬停检测,通过Unity UI自带的事件接口+协程即可实现需求,逻辑完全符合你要的效果:只有悬停满1秒才触发放大,中途离开不会触发任何大小变更。
实现逻辑
- 用
IPointerEnterHandler和IPointerExitHandler两个Unity内置UI事件接口监听光标进出状态 - 光标进入时启动计时协程,协程先等待1秒,再执行放大逻辑
- 光标离开时直接终止计时协程,同时标记悬停状态为false,彻底阻断延迟后的放大触发
注意事项
- 确保Image组件的
Raycast Target属性为勾选状态,否则无法接收UI事件 - 如果存在多层重叠UI,要保证当前Image的渲染层级高于下层UI,避免射线被遮挡
完整代码示例
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using System.Collections; public class HoverScaleTrigger : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { [Header("悬停配置")] public float hoverTriggerDelay = 1f; public Vector3 targetScale = new Vector3(1.2f, 1.2f, 1f); private Vector3 _originalScale; private bool _isHovering; private Coroutine _countCoroutine; private void Awake() { _originalScale = transform.localScale; GetComponent<Image>().raycastTarget = true; } public void OnPointerEnter(PointerEventData eventData) { _isHovering = true; _countCoroutine = StartCoroutine(HoverCount()); } public void OnPointerExit(PointerEventData eventData) { _isHovering = false; if (_countCoroutine != null) { StopCoroutine(_countCoroutine); _countCoroutine = null; } } private IEnumerator HoverCount() { yield return new WaitForSeconds(hoverTriggerDelay); if (_isHovering) { transform.localScale = targetScale; // 需要平滑动画可以替换为DOTween代码(需提前导入DOTween插件) // transform.DOScale(targetScale, 0.2f).SetEase(Ease.OutCubic); } _countCoroutine = null; } }
把上面的脚本挂载到你的Image所在GameObject上即可直接使用,参数可以在Inspector面板自定义调整。
内容的提问来源于stack exchange,提问作者Fast Arrows
相关产品推荐
相关产品推荐

