クリックされた位置にあるUIを全て取得する

Unity

クリックされた位置にあるUIをすべて取得する

UIのコンポーネントを使わずに、スクリプト1つでUIすべてを取得できるので
便利です。(UIが重なっているとき全て取得されることに注意です)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class TestScript : MonoBehaviour
{
    // using UnityEngine.EventSystem を追加すること
    PointerEventData pointer;

    void Start()
    {
        // ポインタ(マウス/タッチ)イベントに関連するイベントの情報
        pointer = new PointerEventData(EventSystem.current);
    }

    void Update()
    {
        // クリックしたら
        if (Input.GetMouseButtonDown(0))
        {
            List<RaycastResult> results = new List<RaycastResult>();

            // マウスポインタの位置にレイ飛ばし、ヒットしたものを保存
            pointer.position = Input.mousePosition;
            EventSystem.current.RaycastAll(pointer, results);

            // ヒットしたUIの名前
            foreach (RaycastResult target in results)
            {
                Debug.Log(target.gameObject.name);
            }
        }
    }
}

コメント

タイトルとURLをコピーしました