Unity - 如何在光标下方制作一系列 UI 游戏对象? [英] Unity - How do I make an array of UI game objects beneath the cursor?
问题描述
我希望能够创建一个数组,该数组包含数组内光标下的所有 UI 元素.这是因为我需要能够判断多个其他 UI 元素下方是否有一个 UI 元素,我尝试了其他技术,但它只显示顶部的 UI 元素.
I want to be able to make an array, which has all the UI elements, under the cursor , inside the array. This is because I need to be able to tell if there is a UI element beneath multiple other UI elements, I've tried other techniques, but it only shows the UI element on top.
为了更清楚,我正在尝试列出位于光标下方的所有 UI 部分,而不仅仅是能够分辨哪个 UI 位于顶部.
推荐答案
听起来您正在寻找 UI.GraphicRaycaster.Raycast
.
Sounds like you are looking for UI.GraphicRaycaster.Raycast
.
GraphicRaycaster
通常附加到每个 Canvas
(否则你将无法与其中的任何内容交互).
The GraphicRaycaster
is usually attached to each Canvas
(otherwise you wouldn't be able to interact with anything in them).
因此,无需引用特定的画布,您就可以将它们全部获取:
So without referencing a specific canvas you could just go and get them all:
// Because this is dynamically changing I recommend to stick to a List instead of an array
private List<RaycastResult> _hits = new List<RaycastResult>();
private EventSystem _eventSystem;
private void Awake()
{
//Fetch the Event System from the Scene
_eventSystem = FindObjectOfType<EventSystem>();
}
private void Update()
{
//Check if the left Mouse button is clicked
if (Input.GetKeyDown(KeyCode.Mouse0))
{
//Set up the new Pointer Event
var eventData = new PointerEventData(_eventSystem) {position = Input.mousePosition};
//Create a list of Raycast Results
_hits.Clear();
// Get all existing graphicsRaycaster
// NOTE: Of course you should rather cache this result e.g. in Awake
// and only update it if a Canvas is added to or removed from the scene
var graphicsRaycasters = FindObjectsOfType<GraphicRaycaster>();
foreach(var graphicsRaycaster in graphicsRaycasters)
{
graphicsRaycaster.Raycast(eventData, _hits);
}
// Do something with the hits
foreach (var result in _hits)
{
Debug.Log(result.gameObject.name, result.gameObject);
}
}
}
这篇关于Unity - 如何在光标下方制作一系列 UI 游戏对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!