2017年10月31日 星期二

Unity內用Pointer方式來偵測非互動型的UGUI

在UGUI內像是Button或Slidert等這種可以讓使用者操控的介面,都會有Interactable這個設定,同時也可以使用下列的程式碼偵測到點擊:

  1. if (Input.GetMouseButtonDown(0))
  2. {
  3.     if (EventSystem.current.currentSelectedGameObject != null)
  4.     {
  5.         Debug.Log(EventSystem.current.currentSelectedGameObject);
  6.     }
  7. }
但是像Image或Rawimage等這種非互動類型的介面,無法用上述的方式偵測到,但偏偏有需要的話該怎麼辦?

首先想到的是從Raycast Target這個設定著手,但意外地我無法使用2DRaycast等方式去偵測(應該是要可以才對,是我人品太糟?):

然後發現了Pointer和其相關方式,因此使用了一下,效果就和Button的OnClick一樣:



使用EventTrigger有很多種觸發方式,相當好用:

最後,如果即時創造UGUI,並且需要即時賦予點擊時回傳的參數時,上面那些事先設定的方式就沒法用了,因此查詢一下各種作法後,發現下面這種方式比較適合我。

首先在即時創造的UGUI上,有沒有EventTrigger這個Comoponent都可以,有的話也不要事先添加任何UnityEvent:

然後撰寫下面程式,並將Script附加在該UGUI物件下:
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ImageController : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
  6.  
  7.     void Start ()
  8.     {
  9.  
  10.     }
  11.  
  12.     void Update ()
  13.     {
  14.  
  15.     }
  16.  
  17.     public void OnPointerDown(PointerEventData eventData)
  18.     {
  19.         Debug.Log("Point down = " + this.name);
  20.     }
  21.  
  22.     public void OnPointerUp(PointerEventData eventData)
  23.     {
  24.         Debug.Log("Point up = " + this.name);
  25.     }
  26. }
這樣就等於當點擊這個UGUI時,程式會回傳該UGUI的名稱,或是其他想回傳的相對應資料了。

沒有留言:

張貼留言