2016年6月8日 星期三

Unity內偵測有否點擊到UGUI作出來的介面

Unity現在可使用方便的UGUI功能作介面,而當要操控2D介面或是作3D物件控制時,都是使用滑鼠左鍵;所以一般邏輯為當滑鼠初次點擊在2D介面上時,就不會啟動3D物件控制功能,因此需要偵測滑鼠是否點擊在任何UGUI作出來的2D介面上。

UGUI在創建時,會自動在【Hierarchy】下產生Canvas』和EventSystem』兩個物件,EventSystem』便是用來處理點擊等事件的存在,所以會使用它來得知是否有滑鼠點擊任何UGUI物件,並可取得所點擊的介面物件。


  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.EventSystems;
  4.  
  5. public class MainProcess : MonoBehaviour {
  6.  
  7.     void Update ()
  8.     {
  9.         if( Input.GetMouseButtonDown( 0 ) )
  10.         {
  11.             if( EventSystem.current.IsPointerOverGameObject() )
  12.             {
  13.                 Debug.Log( "有介面被點擊到!" );
  14.                 Debug.Log( EventSystem.current.currentSelectedGameObject );
  15.             }
  16.         }
  17.     }
  18. }

沒有留言:

張貼留言