但是像Image或Rawimage等這種非互動類型的介面,無法用上述的方式偵測到,但偏偏有需要的話該怎麼辦?
- if (Input.GetMouseButtonDown(0))
- {
- if (EventSystem.current.currentSelectedGameObject != null)
- {
- Debug.Log(EventSystem.current.currentSelectedGameObject);
- }
- }
首先想到的是從Raycast Target這個設定著手,但意外地我無法使用2DRaycast等方式去偵測(應該是要可以才對,是我人品太糟?):
然後發現了Pointer和其相關方式,因此使用了一下,效果就和Button的OnClick一樣:


最後,如果即時創造UGUI,並且需要即時賦予點擊時回傳的參數時,上面那些事先設定的方式就沒法用了,因此查詢一下各種作法後,發現下面這種方式比較適合我。
首先在即時創造的UGUI上,有沒有EventTrigger這個Comoponent都可以,有的話也不要事先添加任何UnityEvent:
然後撰寫下面程式,並將Script附加在該UGUI物件下:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class ImageController : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
- void Start ()
- {
- }
- void Update ()
- {
- }
- public void OnPointerDown(PointerEventData eventData)
- {
- Debug.Log("Point down = " + this.name);
- }
- public void OnPointerUp(PointerEventData eventData)
- {
- Debug.Log("Point up = " + this.name);
- }
- }
這樣就等於當點擊這個UGUI時,程式會回傳該UGUI的名稱,或是其他想回傳的相對應資料了。
沒有留言:
張貼留言