RaycastHit问题与画布?

问题描述:

只有当命中的gameobject不在画布中时,此脚本才会在控制台上显示消息。在位于画布内的按钮释放鼠标按钮时,该脚本不会调试任何内容。我怎样才能解决这个问题?RaycastHit问题与画布?

RaycastHit hit; 

void Update() 
{ 
    if(Input.GetMouseButtonUp(0)) 
    { 
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
     //RayHit hit; 
     if(Physics.Raycast(ray, out hit)) 
     { 
      // do what you want 
      Debug.Log(hit.collider.gameObject.tag); 
     } 
    } 
} 
+0

你的意思是说画布和UI一样吗?如果是这样,你只是做错了,请阅读[关于统一用户界面的教程](https://unity3d.com/learn/tutorials/topics/user-interface-ui)。 – Logman

您可以像这样使用来获取单击哪个UI对象。

if (Input.GetMouseButtonDown(0)) 
    { 
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 


     if (EventSystem.current.IsPointerOverGameObject()) 
     { 
      Debug.Log(EventSystem.current.currentSelectedGameObject.GetComponent<Text>().name); 

     } 

EventSystem.current.currentSelectedGameObject.GetComponent()。名称

将返回点击的对象和

EventSystem.current.IsPointerOverGameObject()

将检查一个UI对象是否被点击。