选择UI或场景中的物体

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;
    }
}

在这里插入图片描述
如上图,玩家可以导入该包,在场景中可以预览点击的是场景中对象还是UI中的对象

这是包的地址
未来也会在csdn里面进行更新自己的开发日志,也可能会同步在Gitee中

猜你喜欢

转载自blog.csdn.net/qq_47926835/article/details/127092064