Unity判断点击对象

UI的点击响应是Unity中最基本的操作,UI响应点击事件,在场景中必须有EventSystem和InputModel(通常为StandaloneInputModule)脚本,UI对象必须勾选RaycastTarget。如果Canvas的Render Mode是World Space的话,UI的z轴方向必须和相机朝向一样(不超过90°)!(之前做了个场景,放置了类似广告牌的UI,在场景中由于图片是对称的,不知道什么时候操作翻转了,一直点不到,还看了半天代码...)

 

有时我们需要判断屏幕上是否点击到了UI对象,可以用过EventSystem的IsPointerOverGameObject方法判断。鼠标点击使用以下代码:

复制代码
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (EventSystem.current.IsPointerOverGameObject())
            {
                Debug.Log("Clicked on the UI");
            }
        }
    }
复制代码

手机触碰使用以下代码

复制代码
void Update()
{
  if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
  {
    if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
    {     Debug.Log(
"Touched the UI");     }   }
复制代码

 以上的方式只能知道是否点击UI,但是不能判断具体点击到哪个,如果想知道具体点击到的UI对象可以使用,以下代码。

复制代码
   PointerEventData m_Data = null;
    List<RaycastResult> results = new List<RaycastResult>();
    void Start()
    {
        m_Data = new PointerEventData(EventSystem.current);
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            m_Data.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            EventSystem.current.RaycastAll(m_Data, results);
            for (int i = 0; i < results.Count; ++i)
            {
                Debug.Log(results[i].gameObject.name);
            }
        }
    }
复制代码

 

如果需要判断点击场景物体对象,可以使用射线,对象必须包含Collider组件(包括BoxCollider,SphereCollider等),代码如下。

复制代码
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                Debug.Log(hit.transform.name);
            }             
        }
    }
复制代码

 

posted @   大白菜的菜园子  阅读(1350)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示