Unity笔记之获取鼠标停留的UI和删除按键触发后引用、判断鼠标是否在UI上

需求:鼠标放在UI上,需要获取这个UI物体,以方便进行其他操作。

百度学习了半天,最终拿了一个大哥(添加链接描述)的内容。本文仅作为个人笔记,建议大家直接去这大哥的博客看。不过我记得好像也可以通过继承unity内部的鼠标事件接口获取到物体,但是由于时间紧,等后面有时间或者想起了再加吧。

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

public class NewBehaviourScript : MonoBehaviour
{
    GameObject currentCanvas;
    void Start()
    {
        currentCanvas = gameObject;
    }

    void Update()
    {
        Debug.Log(GetUI(currentCanvas).name);
    }

    /// <summary>
    /// 获取鼠标停留处UI
    /// </summary>
    public static GameObject GetUI(GameObject canvas)
    {
        if (canvas.GetComponent<GraphicRaycaster>() == null) return null;
        PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
        pointerEventData.position = Input.mousePosition;
        GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>();
        List<RaycastResult> results = new List<RaycastResult>();
        gr.Raycast(pointerEventData, results);
        if (results.Count != 0)
        {
            return results[0].gameObject;
        }
        return null;
    }
}

需求2:发现一个小问题,就是在使用UGUI的时候,如果点击了某个按钮之后不进行任何操作直接按键盘上的空格键就相当于再次点击了上一次点击过的那个按键。

所以要解决这个问题我们得把这个unity记录的地方在我们点击触发方法之后就把这个保存的按键给删除引用。

//在需要取消的地方加上这段就可以了
 UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(null, null);

加上这句代码就可以删除引用了。

需求3:判断鼠标是否在UI上

   if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())//如果鼠标在UI上就返回
   {
       return;
   }
posted @   一世癫狂  阅读(13)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示