Seleccionar objetos en la interfaz de usuario o la escena

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEditor;

public class SelctUIObj : MonoBehaviour
{
    
    
    private List<RaycastResult> list = new List<RaycastResult>();//获取当前鼠标点击的UI对象

    private void Update()
    {
    
    
          
        if(Input.GetMouseButtonDown(0))
        {
    
    
            GameObject clickObj = null;
            if (EventSystem.current.IsPointerOverGameObject())//点的是UI,否则是场景中
            {
    
    
                clickObj = GetCurrentSelectGameObject();
            }
            else
            {
    
    
                clickObj = ClickScene();
            }

            if (clickObj == null)
            {
    
    
                print("此时没有点击对象");
                return;
            }
            else
            {
    
    
                print(clickObj.name);
            }
        }
       
    }
    //获取当前选择的物体
    public GameObject GetCurrentSelectGameObject()
    {
    
    
        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.position = Input.mousePosition;
        EventSystem.current.RaycastAll(eventData, list);

        var raycast = FindFirstRaycast(list);

        var obj = ExecuteEvents.GetEventHandler<IEventSystemHandler>(raycast.gameObject);

        if (obj == null)
        {
    
    
            obj = raycast.gameObject;
        }
        return obj;
    }
    //找到该LIST中的第一个物体
    private RaycastResult FindFirstRaycast(List<RaycastResult> list)
    {
    
    
        for (var i = 0; i < list.Count; ++i)
        {
    
    
            if (list[i].gameObject == null)
                continue;

            return list[i];
        }
        return new RaycastResult();
    }

    //此处添加后,可以点击场景中的物体
    private GameObject ClickScene()
    {
    
    
    	//从摄像头发出到鼠标位置的一条射线用来检测,获取检测到的对象
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
    
    
            GameObject go = hit.collider.gameObject;
            return go;
        }

        return null;
    }
}

inserte la descripción de la imagen aquí
Como se muestra en la imagen de arriba, el jugador puede importar el paquete y, en la escena, puede obtener una vista previa de si el objeto en el que se hizo clic es un objeto de la escena o un objeto de la interfaz de usuario.

Esta es la dirección del paquete.
En el futuro, actualizaré mi propio registro de desarrollo en csdn, y también puede sincronizarse en Gitee.

Supongo que te gusta

Origin blog.csdn.net/qq_47926835/article/details/127092064
Recomendado
Clasificación