Unity 获取鼠标下的UI元素:两种常用方法

在Unity中,获取鼠标下的UI元素是常见的需求。本文介绍两种常用的方法:

  1. 使用鼠标位置来射线检测

    首先,获取鼠标的屏幕坐标,然后使用Camera.ScreenPointToRay()方法将屏幕坐标转换为射线。接下来,使用Physics.Raycast()方法来检测射线是否与UI碰撞器相交。如果相交,可以使用hit.collider.gameObject来获取与射线相交的游戏对象,即鼠标下的UI。

    Vector3 mousePosition = Input.mousePosition;
    Ray ray = Camera.main.ScreenPointToRay(mousePosition);
    RaycastHit hit;
    
    if (Physics.Raycast(ray, out hit)) {
        GameObject hitObject = hit.collider.gameObject;
        // 处理鼠标下的UI
    }
    
  2. 使用EventSystem的RaycastAll()方法

    Unity的EventSystem组件提供了一个RaycastAll()方法,可以直接获取所有与鼠标射线相交的UI对象。然后,可以遍历返回的结果,找到最接近摄像机的UI对象。

    PointerEventData eventData = new PointerEventData(EventSystem.current);
    eventData.position = Input.mousePosition;
    
    List<RaycastResult> results = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventData, results);
    
    if (results.Count > 0) {
        GameObject hitObject = results[0].gameObject;
        // 处理鼠标下的UI
    }
    

以上是两种常用的方法来获取鼠标下的UI,你可以根据自己的需求选择其中一种方法来实现。


原文地址: https://www.cveoy.top/t/topic/pkNc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录