unity鼠标悬停在3D模型上时显示介绍面板

一、鼠标悬停在3D模型上时显示介绍面板

1.新建Cube模型,新建Image面板

2.编写脚本OnPointerEnterShow3D.cs,脚本挂载到模型上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class OnPointerEnterShow3D : MonoBehaviour
{
    //要显示的ui
    public RectTransform tip;

    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        bool raycast = Physics.Raycast(ray, out hit);
        if (raycast)
        {
            GameObject go = hit.collider.gameObject;
            if (go == this.gameObject)
            {
                tip.gameObject.SetActive(true);
                FollowMouse();
            }
            else
            {
                tip.gameObject.SetActive(false);
                Destory(go);
            }

        }
        else
        {
            tip.gameObject.SetActive(false);
        }

    }

    //ui位置跟随鼠标实时变化
    void FollowMouse()
    {
        tip.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y + 80f, 0f);
    }

}
3.运行如下

 

二、鼠标悬停在UI上时显示介绍面板

1.新建UI结构

2.编写脚本OnPointerEnterShowUI.cs,将脚本挂载到需要鼠标悬停的UI上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class OnPointerEnterShowUI : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("移入");
        transform.GetChild(1).gameObject.SetActive(true);
    }
    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("移出");
        transform.GetChild(1).gameObject.SetActive(false);
    }
}
3.运行如下

 

猜你喜欢

转载自blog.csdn.net/qq_2633600317/article/details/131853036