标签:对象 void 点击 results EventSystem Unity UI Input
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); } } }
标签:对象,void,点击,results,EventSystem,Unity,UI,Input 来源: https://www.cnblogs.com/RollingInTheCode/p/16193113.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。