Unity判断点击对象

2022/4/29 6:14:21

本文主要是介绍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);
            }             
        }
    }

 



这篇关于Unity判断点击对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程